Coverage for geoparser/db/db.py: 100%
48 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 18:08 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 18:08 +0000
1from __future__ import annotations
3import os
4import sqlite3
5from contextlib import contextmanager
6from pathlib import Path
7from typing import Iterator
9from appdirs import user_data_dir
10from sqlalchemy import Engine, event, text
11from sqlalchemy.engine import Connection
12from sqlalchemy.pool import NullPool
13from sqlmodel import Session, create_engine
15import geoparser.db.models # noqa: F401
16from geoparser.db.models.base import geoparser_registry
18# Database URL configuration (SQLite)
19DATABASE_URL = os.getenv(
20 "DATABASE_URL",
21 f"sqlite:///{Path(user_data_dir('geoparser', '')) / 'geoparser.db'}",
22)
24# Ensure parent directory exists
25db_path = DATABASE_URL.replace("sqlite:///", "")
26Path(db_path).parent.mkdir(parents=True, exist_ok=True)
29# Event listener for SQLite foreign keys
30# This applies to ALL Engine instances (including test engines)
31@event.listens_for(Engine, "connect")
32def _set_sqlite_pragma(dbapi_connection, connection_record):
33 """
34 Configure SQLite connections on connect.
36 Enables foreign key enforcement for all SQLite connections.
38 Args:
39 dbapi_connection: Database API connection object
40 connection_record: SQLAlchemy connection record
41 """
42 if isinstance(dbapi_connection, sqlite3.Connection):
43 cursor = dbapi_connection.cursor()
44 cursor.execute("PRAGMA foreign_keys=ON")
45 cursor.close()
48# Create engine once at module level
49engine: Engine = create_engine(
50 DATABASE_URL,
51 echo=False, # Set to True for SQL debugging
52 connect_args={"check_same_thread": False},
53 poolclass=NullPool, # NullPool is recommended for SQLite
54 pool_pre_ping=True, # Keeps connections fresh for long-lived apps
55)
58def _check_database_compatibility() -> None:
59 """
60 Fail early if the database was created by an incompatible older version.
62 Older releases stored gazetteer data (gazetteer/source/feature/name tables)
63 inside this database and linked referents to it via a feature foreign key.
64 Gazetteers now live in separate artifact files, so such databases cannot be
65 used as-is.
67 Raises:
68 RuntimeError: If a legacy database layout is detected.
69 """
70 with engine.connect() as connection:
72 def _table_exists(name: str) -> bool:
73 result = connection.execute(
74 text("SELECT 1 FROM sqlite_master WHERE type='table' AND name=:name"),
75 {"name": name},
76 )
77 return result.first() is not None
79 def _table_has_column(table: str, column: str) -> bool:
80 result = connection.execute(
81 text(f"SELECT 1 FROM pragma_table_info('{table}') WHERE name=:column"),
82 {"column": column},
83 )
84 return result.first() is not None
86 legacy_gazetteer_tables = any(
87 _table_exists(name) for name in ("gazetteer", "source", "feature", "name")
88 )
89 legacy_referent_layout = _table_exists("referent") and not _table_has_column(
90 "referent", "feature_identifier"
91 )
93 if legacy_gazetteer_tables or legacy_referent_layout:
94 raise RuntimeError(
95 "Your geoparser database was created by an older version and is not compatible "
96 "with this release:\n\n"
97 f"{db_path}\n\n"
98 "The Irchel Geoparser is still in active development, and the database format "
99 "may change between releases. There is no automatic upgrade path yet, so you "
100 "will need to delete the database file and reinstall the gazetteers to continue. "
101 "Doing so also removes any projects and results stored in the database. "
102 )
105def create_db_and_tables() -> None:
106 """
107 Create the core Geoparser tables.
109 Tables come from the package registry, so models a host application
110 registers on ``SQLModel.metadata`` are not created here.
111 """
112 _check_database_compatibility()
113 geoparser_registry.metadata.create_all(engine)
116@contextmanager
117def get_session() -> Iterator[Session]:
118 """
119 Get a database session using context manager pattern.
121 This is the preferred way to get a database session. The session
122 is automatically closed when the context exits.
124 Yields:
125 SQLModel Session for database operations
126 """
127 session = Session(engine, expire_on_commit=False)
128 try:
129 yield session
130 finally:
131 session.close()
134@contextmanager
135def get_connection() -> Iterator[Connection]:
136 """
137 Get a database connection using context manager pattern.
139 For operations that need direct connection access (like executing raw
140 SQL). This is the preferred way to get a connection as it accesses the
141 engine at runtime, respecting any patches applied during testing.
143 Yields:
144 SQLAlchemy Connection for database operations
145 """
146 with engine.connect() as connection:
147 yield connection