File size: 2,925 Bytes
4c49d30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdb6bd0
4c49d30
 
 
 
 
 
 
 
 
 
fdb6bd0
4c49d30
 
fdb6bd0
4c49d30
 
 
 
 
 
 
fdb6bd0
4c49d30
fdb6bd0
4c49d30
fdb6bd0
4c49d30
 
 
 
fdb6bd0
4c49d30
 
 
 
 
 
fdb6bd0
4c49d30
 
 
 
 
 
 
 
 
 
fdb6bd0
4c49d30
 
 
 
 
 
 
 
fdb6bd0
4c49d30
 
 
 
fdb6bd0
4c49d30
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"""
Database Initialization Script
Creates necessary tables and indexes in Turso database
"""

import asyncio
import os
import sys
from pathlib import Path

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from app.services.database_service import DatabaseService
from dotenv import load_dotenv

load_dotenv()


async def run_migration(db: DatabaseService):
    """Run schema migration to add multi-country columns if missing"""
    print("\nRunning schema migration...")
    
    migration_queries = [
        ("exchange_name", "ALTER TABLE stocks ADD COLUMN exchange_name TEXT DEFAULT ''"),
        ("country", "ALTER TABLE stocks ADD COLUMN country TEXT DEFAULT 'us'"),
        ("yfinance_suffix", "ALTER TABLE stocks ADD COLUMN yfinance_suffix TEXT DEFAULT ''"),
    ]
    
    for col_name, alter_sql in migration_queries:
        try:
            await db._execute(alter_sql)
            print(f"  Added column: {col_name}")
        except Exception:
            # Column already exists - that's fine
            print(f"  Column already exists: {col_name}")

    # Create country index if not exists
    try:
        await db._execute("""
            CREATE INDEX IF NOT EXISTS idx_stocks_country
            ON stocks(country)
        """)
        print("  Created index: idx_stocks_country")
    except Exception as e:
        print(f"  Index already exists or could not be created: {e}")

    print("  Migration complete")


async def main():
    """Initialize database schema"""
    print("Initializing database...")
    
    # Get credentials from environment
    turso_url = os.getenv("TURSO_URL")
    turso_token = os.getenv("TURSO_TOKEN")
    
    if not turso_url or not turso_token:
        print("Error: TURSO_URL and TURSO_TOKEN must be set in .env file")
        sys.exit(1)
    
    # Initialize database service
    db = DatabaseService(url=turso_url, token=turso_token)
    
    try:
        await db.initialize()
        # Run migration to add multi-country columns
        await run_migration(db)
        
        print("\nDatabase initialized successfully!")
        print("\nCreated/updated tables:")
        print("  - forecasts (cached predictions)")
        print("  - stocks (stock metadata with multi-country support)")
        print("\nNew columns added:")
        print("  - exchange_name: Full exchange name")
        print("  - country: Country code (us, uk, ca, au, nz, ie)")
        print("  - yfinance_suffix: yfinance ticker suffix")
        print("\nNext steps:")
        print("  1. Run: python scripts/seed_all_stocks.py")
        print("     (This seeds stocks from all 6 countries)")
        print("  2. Start the API: uvicorn app.main:app --reload")
        
    except Exception as e:
        print(f"Initialization failed: {e}")
        sys.exit(1)
    finally:
        await db.close()


if __name__ == "__main__":
    asyncio.run(main())