33from loguru import logger
44
55from climate_ref .config import Config
6- from climate_ref .database import Database , _get_database_revision
6+ from climate_ref .database import Database , MigrationState
77from climate_ref .provider_registry import ProviderRegistry
88from ref_backend .core .config import Settings
99
@@ -20,26 +20,47 @@ def get_ref_config(settings: Settings) -> Config:
2020 return Config .load (config_fname , allow_missing = True )
2121
2222
23- def get_database (ref_config : Config ) -> Database :
23+ def get_database (ref_config : Config , read_only : bool = False ) -> Database :
2424 """
25- Get a database connection using the default config
25+ Get a database connection using the default config.
26+
27+ When ``read_only`` is true,
28+ the SQLite database is opened via``Database.from_config(..., read_only=True)``,
29+ which rewrites the URL to read-only URI form so no journal/WAL sidecar is created.
2630 """
27- database = Database .from_config (ref_config , run_migrations = False )
28- with database ._engine .connect () as connection :
29- if _get_database_revision (connection ) is None :
30- msg = (
31- "The database migration has not been run. "
32- "Check the database URL in your config file and run the migration."
33- )
34- logger .warning (msg )
35- if ref_config .db .run_migrations :
36- raise ValueError (msg )
31+ database = Database .from_config (ref_config , run_migrations = False , read_only = read_only )
32+
33+ status = database .migration_status (ref_config )
34+ state = status ["state" ]
35+ if state is MigrationState .UP_TO_DATE :
36+ return database
37+
38+ if state is MigrationState .UNMANAGED :
39+ msg = (
40+ "The database has no alembic revision stamp. "
41+ "Check the database URL in your config file and run the migration."
42+ )
43+ logger .warning (msg )
44+ if ref_config .db .run_migrations :
45+ raise ValueError (msg )
46+ elif state is MigrationState .REMOVED :
47+ raise ValueError (
48+ f"Database revision { status ['current' ]!r} has been removed. "
49+ "Please delete your database and start again."
50+ )
51+ else :
52+ logger .warning (
53+ f"Database revision { status ['current' ]!r} does not match this image's "
54+ f"head revision { status ['head' ]!r} . "
55+ "The API will continue to read this database."
56+ )
57+
3758 return database
3859
3960
40- def get_provider_registry (ref_config : Config ) -> ProviderRegistry :
61+ def get_provider_registry (ref_config : Config , read_only : bool = False ) -> ProviderRegistry :
4162 """
4263 Get the provider registry
4364 """
44- database = get_database (ref_config )
65+ database = get_database (ref_config , read_only = read_only )
4566 return ProviderRegistry .build_from_config (ref_config , database )
0 commit comments