Skip to main content

pgs.py — Database Layer

Thin wrapper around psycopg2 and SQLAlchemy providing connection management and CRUD operations used by all other modules.


Functions

Connection

conn(auto=True) → psycopg2.connection

Opens a direct psycopg2 connection to the application database (Config.DB_NAME).

con = pgs.conn() # autocommit = True
con = pgs.conn(auto=False) # manual commit required

Reads config from Config.DB_HOST, Config.DB_PORT, Config.DB_NAME, Config.DB_USER, Config.DB_PASS.

Use 127.0.0.1 not localhost on VPS

When PostgreSQL runs in Docker, localhost triggers Unix socket lookup which fails. Set VPS_DB_HOST=127.0.0.1 in backend/.env.

database_conn(dbname, auto=True) → psycopg2.connection

Same as conn() but accepts dbname as a parameter. Useful for connecting to databases other than the default.

Read

read_sql(sql, ...) → DataFrame

Executes a SQL query via SQLAlchemy and returns a pandas DataFrame.

df = pgs.read_sql("SELECT masid, mname FROM scr_master WHERE typ = 1")
df = pgs.read_sql("SELECT * FROM scr_nseeq_eod WHERE sdate = :dt",
params={"dt": "2026-05-22"})

Accepts all parameters of pd.read_sql_query (index_col, parse_dates, chunksize, etc.). Internally creates a fresh SQLAlchemy engine per call — no connection pooling.

getsqlValue(sql, all=True) → tuple | None

Lightweight single-value query using psycopg2. Returns fetchall() or fetchone().

# Single value (all=False → fetchone)
result = pgs.getsqlValue("SELECT MAX(sdate) FROM scr_nseeq_eod", False)
max_date = result[0] if result else None

# Multiple rows (all=True → fetchall)
rows = pgs.getsqlValue("SELECT masid, mname FROM scr_master WHERE typ=1")

Write

insertdataframe(connection, df, table) → bool

Bulk-inserts a DataFrame into table using psycopg2.extras.execute_values (page_size=2000 for efficiency). Rolls back on error.

pgs.insertdataframe(conn, df, 'scr_master')

Also accepts a list of dicts instead of a DataFrame.

updatetable_from_df(connection, df, table, deleteSQL="", fdate="", tdate="") → bool

Delete-then-insert pattern:

Used for daily upsert: delete the day's existing rows, then insert fresh data.

update_or_delete_sql(mSql, connection) → bool

Executes a raw UPDATE or DELETE statement. Commits on success, rolls back on error.

Schema Check

checktableexists(connection, tName) → bool

Checks information_schema.tables for table existence.

checktables(connection)

Checks for categories table and creates it from keywords.csv if missing. Legacy function — likely unused in current codebase. See Junk Analysis.


Connection Architecture

Note: psycopg2 is used for writes (insert/update/delete) and single-value reads. SQLAlchemy is used only for read_sql (pandas DataFrames).


Frequently Used Tables Reference

scr_master — Security Master

ColumnTypeDescription
masidSERIAL PKAuto-increment ID
mnameVARCHARSymbol name (e.g., NIFTY, RELIANCE)
typINT1=EQ, 2=Index, 3=FUTIDX, 4=FUTSTK, 5=OPTIDX, 6=OPTSTK
underlyINTFK → masid of underlying (for F&O)
edateVARCHARExpiry string (DDMONYY format)
monthindexINT0=spot, 1/-I=near month, 2/-II=mid, 3/-III=far
strikeFLOATStrike price (options only)
opttypVARCHARCE or PE (options only)

scr_nseeq_eod — Equity EOD

ColumnTypeDescription
masidINT FK→ scr_master
sdateDATETrading date
sopenFLOATOpen price
shighFLOATHigh price
slowFLOATLow price
scloseFLOATClose price
svolumeFLOATVolume (shares traded)
svalueFLOATTurnover value
slastFLOATLast traded price
prevcloseFLOATPrevious close
delqtyFLOATDeliverable quantity
avgpriceFLOATAverage price (svalue/svolume)
f5minFLOATFirst 5-min OHLCV (reserved)
f15minFLOATFirst 15-min (reserved)
l5minFLOATLast 5-min (reserved)
l15minFLOATLast 15-min (reserved)

scr_nsefo_eod — F&O EOD

ColumnTypeDescription
masidINT FK→ scr_master
sdateDATETrading date
sopen/shigh/slow/scloseFLOATOHLC
svolumeFLOATContracts traded
svaluelFLOATValue in lakhs
oiFLOATOpen interest
coiFLOATChange in open interest
avgpriceFLOATAverage price
lotsizeINTLot size (reserved, default 0)

scr_indexpepb — Index PE/PB

ColumnTypeDescription
masidINT FK→ scr_master (index only)
sdateDATEDate
peFLOATPrice-to-Earnings ratio
pbFLOATPrice-to-Book ratio
divyieFLOATDividend yield

tasks — Retry Queue

ColumnTypeDescription
tidSERIAL PKTask ID
typINT1=IndexTask, 2=EquityTask, 3=DelVolTask, 4=NSESiteTask, 5=FOTask
notesTEXTDescription
taskobjJSONB{"YYYY-MM-DD": {"retries": N, "lasttry": "YYYY-MM-DD"}}

holidays

ColumnTypeDescription
sdateDATEHoliday date
exchINTExchange (1=NSE)
detailsTEXTHoliday name/description

specialdays — Muhurat Trading

ColumnTypeDescription
sdateDATEMuhurat date
exchINT1=NSE
starttimeTIMESession start
endtimeTIMESession end
detailsTEXTDescription