"""Integration tests for SQLite-backed DataTable loading."""

from pathlib import Path
import sqlite3
import tempfile

from soigia.datatable import DataTable


def test_from_sqlite_db_can_read_real_sqlite_file():
    db_path = None
    handle = tempfile.NamedTemporaryFile(dir=Path.cwd(), suffix=".db", delete=False)
    try:
        db_path = Path(handle.name)
        handle.close()

        connection = sqlite3.connect(str(db_path))
        try:
            connection.execute(
                "CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER NOT NULL)"
            )
            connection.executemany(
                "INSERT INTO users (name, age) VALUES (?, ?)",
                [("alice", 19), ("bob", 24), ("carol", 31)],
            )
            connection.commit()
        finally:
            connection.close()

        table = DataTable.from_sqlite_db(
            "SELECT name, age FROM users ORDER BY id",
            connection_string=f"sqlite:///{db_path.as_posix()}",
        )

        assert isinstance(table, DataTable)
        assert table.to_rows() == [
            {"name": "alice", "age": 19},
            {"name": "bob", "age": 24},
            {"name": "carol", "age": 31},
        ]
    finally:
        if handle and not handle.closed:
            handle.close()
        if db_path is not None and db_path.exists():
            db_path.unlink()
