"""SQLite DB-API compatibility helpers.

Some runtime images ship a stdlib ``sqlite3`` module linked against a
system ``libsqlite3`` that is missing newer APIs such as
``sqlite3_deserialize``. When that happens, importing or using the stdlib
driver can fail before the backend even starts.

We fall back to ``pysqlite3`` when available so the backend keeps working
with a self-contained SQLite build.
"""

from __future__ import annotations

import sys

SQLITE_DRIVER = "pysqlite3"


def _load_sqlite_module():
    global SQLITE_DRIVER
    try:
        import pysqlite3 as sqlite_package
        import pysqlite3.dbapi2 as sqlite_module

        sys.modules["sqlite3"] = sqlite_package
        sys.modules["sqlite3.dbapi2"] = sqlite_module
    except Exception:
        import sqlite3 as sqlite_module

        SQLITE_DRIVER = "native sqlite3"
    return sqlite_module


sqlite3 = _load_sqlite_module()
