Repository: pola-rs/polars
File: py-polars/polars/dataframe/frame.py (Python)

Code before:
                engine = "sqlalchemy"
            elif connection_module_root.startswith("adbc"):
                engine = "adbc"

        def unpack_table_name(name: str) -> tuple[str | None, str | None, str]:
            """Unpack optionally qualified table name to catalog/schema/table tuple."""
            from csv import reader as delimited_read

            components: list[str | None] = next(delimited_read([name], delimiter="."))  # type: ignore[arg-type]
            if len(components) > 3:
                msg = f"`table_name` appears to be invalid: '{name}'"
                raise ValueError(msg)
            catalog, schema, tbl = ([None] * (3 - len(components))) + components
            return catalog, schema, tbl  # type: ignore[return-value]

        if engine == "adbc":
            from polars.io.database._utils import (
                _get_adbc_module_name_from_uri,
                _import_optional_adbc_driver,
                _open_adbc_connection,
            )

            conn, can_close_conn = (
                (_open_adbc_connection(connection), True)
                if isinstance(connection, str)
                else (connection, False)
            )

            driver_manager = import_optional("adbc_driver_manager")
            driver_manager_str_version = getattr(driver_manager, "__version__", "0.0")
            driver_manager_version = parse_version(driver_manager_str_version)

            if if_table_exists == "fail":
                # if the table exists, 'create' will raise an error,
                # resulting in behaviour equivalent to 'fail'
                mode = "create"
            elif if_table_exists == "replace":
                if driver_manager_version < (0, 7):
                    msg = (
                        "`if_table_exists = 'replace'` requires ADBC version >= 0.7, "
                        f"found {driver_manager_str_version}"
                    )
                    raise ModuleUpgradeRequiredError(msg)
                mode = "replace"
            elif if_table_exists == "append":
                mode = "append"
            else:
                msg = (
                    f"unexpected value for `if_table_exists`: {if_table_exists!r}"
                    f"\n\nChoose one of {{'fail', 'replace', 'append'}}"
                )

Review comment (suggestion):
doing this before importing `adbc-driver-manager` fixes https://github.com/pola-rs/polars/issues/24118.
The context manager is still entered later (line 4306)

Code after:
                engine = "sqlalchemy"
            elif connection_module_root.startswith("adbc"):
                engine = "adbc"

        def unpack_table_name(name: str) -> tuple[str | None, str | None, str]:
            """Unpack optionally qualified table name to catalog/schema/table tuple."""
            from csv import reader as delimited_read

            components: list[str | None] = next(delimited_read([name], delimiter="."))  # type: ignore[arg-type]
            if len(components) > 3:
                msg = f"`table_name` appears to be invalid: '{name}'"
                raise ValueError(msg)
            catalog, schema, tbl = ([None] * (3 - len(components))) + components
            return catalog, schema, tbl  # type: ignore[return-value]

        if engine == "adbc":
            from polars.io.database._utils import (
                _get_adbc_module_name_from_uri,
                _import_optional_adbc_driver,
                _open_adbc_connection,
            )

            conn, can_close_conn = (
                (_open_adbc_connection(connection), True)
                if isinstance(connection, str)
                else (connection, False)
            )

            driver_manager = import_optional("adbc_driver_manager")

            # base class for ADBC connections
            if not isinstance(conn, driver_manager.dbapi.Connection):
                msg = f"unrecognised connection type {connection!r}"
                raise TypeError(msg)

            driver_manager_str_version = getattr(driver_manager, "__version__", "0.0")
            driver_manager_version = parse_version(driver_manager_str_version)

            if if_table_exists == "fail":
                # if the table exists, 'create' will raise an error,
                # resulting in behaviour equivalent to 'fail'
                mode = "create"
            elif if_table_exists == "replace":
                if driver_manager_version < (0, 7):
                    msg = (
                        "`if_table_exists = 'replace'` requires ADBC version >= 0.7, "
                        f"found {driver_manager_str_version}"
                    )
                    raise ModuleUpgradeRequiredError(msg)
                mode = "replace"
            elif if_table_exists == "append":