From a673fc500876f21899de2e8a8113f9a3c1b4f390 Mon Sep 17 00:00:00 2001 From: Bill Date: Tue, 4 Nov 2025 07:09:09 -0500 Subject: [PATCH] feat: auto-initialize trading_days schema on database creation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- api/database.py | 29 ++++++++++++++++++ .../test_database_initialization.py | 30 +++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 tests/integration/test_database_initialization.py diff --git a/api/database.py b/api/database.py index 830f0c1..3c6e301 100644 --- a/api/database.py +++ b/api/database.py @@ -560,6 +560,35 @@ class Database: self.connection = sqlite3.connect(db_path, check_same_thread=False) self.connection.row_factory = sqlite3.Row + # Auto-initialize schema if needed + self._initialize_schema() + + def _initialize_schema(self): + """Initialize database schema if tables don't exist.""" + import importlib.util + import os + + # Check if trading_days table exists + cursor = self.connection.execute( + "SELECT name FROM sqlite_master WHERE type='table' AND name='trading_days'" + ) + + if cursor.fetchone() is None: + # Schema doesn't exist, create it + # Import migration module using importlib (module name starts with number) + migration_path = os.path.join( + os.path.dirname(__file__), + 'migrations', + '001_trading_days_schema.py' + ) + spec = importlib.util.spec_from_file_location( + "trading_days_schema", + migration_path + ) + migration_module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(migration_module) + migration_module.create_trading_days_schema(self) + def create_trading_day( self, job_id: str, diff --git a/tests/integration/test_database_initialization.py b/tests/integration/test_database_initialization.py new file mode 100644 index 0000000..71cc4d4 --- /dev/null +++ b/tests/integration/test_database_initialization.py @@ -0,0 +1,30 @@ +import pytest +from api.database import Database + + +class TestDatabaseInitialization: + + def test_database_creates_new_schema_on_init(self, tmp_path): + """Test database automatically creates trading_days schema.""" + db_path = tmp_path / "new.db" + + # Create database (should auto-initialize schema) + db = Database(str(db_path)) + + # Verify trading_days table exists + cursor = db.connection.execute( + "SELECT name FROM sqlite_master WHERE type='table' AND name='trading_days'" + ) + assert cursor.fetchone() is not None + + # Verify holdings table exists + cursor = db.connection.execute( + "SELECT name FROM sqlite_master WHERE type='table' AND name='holdings'" + ) + assert cursor.fetchone() is not None + + # Verify actions table exists + cursor = db.connection.execute( + "SELECT name FROM sqlite_master WHERE type='table' AND name='actions'" + ) + assert cursor.fetchone() is not None