|
| 1 | +import os |
| 2 | + |
| 3 | +import sqlalchemy |
| 4 | +import sqlalchemy.orm |
| 5 | +import sqlite3 |
| 6 | + |
| 7 | +class Session: |
| 8 | + def __init__(self, url, **engine_kwargs): |
| 9 | + self._url = url |
| 10 | + if _is_sqlite_url(self._url): |
| 11 | + _assert_sqlite_file_exists(self._url) |
| 12 | + |
| 13 | + self._engine = _create_engine(self._url, **engine_kwargs) |
| 14 | + self._is_postgres = self._engine.url.get_backend_name() in {"postgres", "postgresql"} |
| 15 | + _setup_on_connect(self._engine) |
| 16 | + self._session = _create_scoped_session(self._engine) |
| 17 | + |
| 18 | + |
| 19 | + def is_postgres(self): |
| 20 | + return self._is_postgres |
| 21 | + |
| 22 | + |
| 23 | + def execute(self, statement): |
| 24 | + return self._session.execute(sqlalchemy.text(str(statement))) |
| 25 | + |
| 26 | + |
| 27 | + def __getattr__(self, attr): |
| 28 | + return getattr(self._session, attr) |
| 29 | + |
| 30 | + |
| 31 | +def _is_sqlite_url(url): |
| 32 | + return url.startswith("sqlite:///") |
| 33 | + |
| 34 | + |
| 35 | +def _assert_sqlite_file_exists(url): |
| 36 | + path = url[len("sqlite:///"):] |
| 37 | + if not os.path.exists(path): |
| 38 | + raise RuntimeError(f"does not exist: {path}") |
| 39 | + if not os.path.isfile(path): |
| 40 | + raise RuntimeError(f"not a file: {path}") |
| 41 | + |
| 42 | + |
| 43 | +def _create_engine(url, **kwargs): |
| 44 | + try: |
| 45 | + engine = sqlalchemy.create_engine(url, **kwargs) |
| 46 | + except sqlalchemy.exc.ArgumentError: |
| 47 | + raise RuntimeError(f"invalid URL: {url}") from None |
| 48 | + |
| 49 | + engine.execution_options(autocommit=False) |
| 50 | + return engine |
| 51 | + |
| 52 | + |
| 53 | +def _setup_on_connect(engine): |
| 54 | + def connect(dbapi_connection, _): |
| 55 | + _disable_auto_begin_commit(dbapi_connection) |
| 56 | + if _is_sqlite_connection(dbapi_connection): |
| 57 | + _enable_sqlite_foreign_key_constraints(dbapi_connection) |
| 58 | + |
| 59 | + sqlalchemy.event.listen(engine, "connect", connect) |
| 60 | + |
| 61 | + |
| 62 | +def _create_scoped_session(engine): |
| 63 | + session_factory = sqlalchemy.orm.sessionmaker(bind=engine) |
| 64 | + return sqlalchemy.orm.scoping.scoped_session(session_factory) |
| 65 | + |
| 66 | + |
| 67 | +def _disable_auto_begin_commit(dbapi_connection): |
| 68 | + # Disable underlying API's own emitting of BEGIN and COMMIT so we can ourselves |
| 69 | + # https://docs.sqlalchemy.org/en/13/dialects/sqlite.html#serializable-isolation-savepoints-transactional-ddl |
| 70 | + dbapi_connection.isolation_level = None |
| 71 | + |
| 72 | + |
| 73 | +def _is_sqlite_connection(dbapi_connection): |
| 74 | + return isinstance(dbapi_connection, sqlite3.Connection) |
| 75 | + |
| 76 | + |
| 77 | +def _enable_sqlite_foreign_key_constraints(dbapi_connection): |
| 78 | + cursor = dbapi_connection.cursor() |
| 79 | + cursor.execute("PRAGMA foreign_keys=ON") |
| 80 | + cursor.close() |
0 commit comments