Download database.py from adoomy/StocKing: direct link, hf CLI and curl.
- Browser
- Download file 2.05 kB
-
https://huggingface.co/spaces/adoomy/StocKing/resolve/main/database.py
- Command line
-
hf download hf://spaces/adoomy/StocKing/database.py
-
curl -L -o database.py https://huggingface.co/spaces/adoomy/StocKing/resolve/main/database.py
2.05 kB
| import os | |
| from sqlalchemy import create_engine, event, text | |
| from sqlalchemy.orm import sessionmaker | |
| from dotenv import load_dotenv | |
| from models import Base | |
| load_dotenv() | |
| DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./stocking.db") | |
| _is_postgres = DATABASE_URL.startswith("postgresql") | |
| connect_args = ( | |
| {"sslmode": "require"} if _is_postgres | |
| else {"check_same_thread": False, "timeout": 30} | |
| ) | |
| engine = create_engine(DATABASE_URL, connect_args=connect_args, pool_pre_ping=True) | |
| # SQLite ์ ์ฉ: WAL ๋ชจ๋ (PostgreSQL์๋ ์ ์ฉ ์ ํจ) | |
| if not _is_postgres: | |
| def set_wal_mode(dbapi_connection, connection_record): | |
| """WAL ๋ชจ๋: ์ค์ผ์ค๋ฌ write + API read ๋์ ์ฒ๋ฆฌ ๊ฐ๋ฅ.""" | |
| cursor = dbapi_connection.cursor() | |
| cursor.execute("PRAGMA journal_mode=WAL") | |
| cursor.close() | |
| SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) | |
| def init_db(): | |
| # watchlist ํ ์ด๋ธ ์คํค๋ง ๋ง์ด๊ทธ๋ ์ด์ : SQLite์๋ง ์ ์ฉ (PostgreSQL์ PRAGMA ์์) | |
| if not _is_postgres: | |
| with engine.connect() as conn: | |
| cols = [row[1] for row in conn.execute(text("PRAGMA table_info(watchlist)")).fetchall()] | |
| if cols and "user_id" not in cols: | |
| conn.execute(text("DROP TABLE watchlist")) | |
| conn.commit() | |
| Base.metadata.create_all(bind=engine) | |
| # annual_data ์ธ๋ฑ์ค ๋ง์ด๊ทธ๋ ์ด์ : create_all์ ๊ธฐ์กด ํ ์ด๋ธ์ ์ธ๋ฑ์ค๋ฅผ ์ถ๊ฐํ์ง ์์ผ๋ฏ๋ก ์ง์ ์์ฑ | |
| with engine.connect() as conn: | |
| conn.execute(text( | |
| "CREATE INDEX IF NOT EXISTS ix_annual_data_ticker_year_is_estimate " | |
| "ON annual_data (ticker, year, is_estimate)" | |
| )) | |
| conn.execute(text( | |
| "CREATE INDEX IF NOT EXISTS ix_annual_data_ticker_is_estimate " | |
| "ON annual_data (ticker, is_estimate)" | |
| )) | |
| conn.commit() | |
| def get_db(): | |
| db = SessionLocal() | |
| try: | |
| yield db | |
| finally: | |
| db.close() | |