File size: 3,617 Bytes
ba71465
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""DuckDB helpers for the migration prototype."""
from __future__ import annotations

from pathlib import Path
from typing import Dict, List

import duckdb

DB_PATH = Path(__file__).resolve().parent.parent / "off_quality.db"
TABLE_NAME = "nutrition_table"

SCHEMA_SQL = f"""

CREATE TABLE IF NOT EXISTS {TABLE_NAME} (

    product_id TEXT,

    energy_kj DOUBLE,

    energy_kj_computed DOUBLE,

    energy_kcal DOUBLE,

    fat DOUBLE,

    saturated_fat DOUBLE,

    carbohydrates DOUBLE,

    sugars DOUBLE,

    starch DOUBLE,

    sodium DOUBLE,

    ingredients_text TEXT,

    ingredients_text_present INTEGER,

    contains_statement_present INTEGER,

    allergen_evidence_present INTEGER,

    fop_threshold_exceeded INTEGER,

    fop_symbol_present INTEGER,

    fop_exempt_proxy INTEGER,

    product_is_prepackaged_proxy INTEGER,

    lc TEXT,

    lang TEXT,

    language_code TEXT

)

"""


def connect(db_path: Path = DB_PATH) -> duckdb.DuckDBPyConnection:
    return duckdb.connect(db_path.as_posix())


def recreate_nutrition_table(db_path: Path = DB_PATH) -> None:
    """Drop and recreate the main table for deterministic runs."""
    with connect(db_path) as con:
        con.execute(f"DROP TABLE IF EXISTS {TABLE_NAME}")
        con.execute(SCHEMA_SQL)


def load_jsonl_to_duckdb(jsonl_path: Path, db_path: Path = DB_PATH) -> None:
    """Load JSONL records into DuckDB."""
    with connect(db_path) as con:
        con.execute(
            f"""

            INSERT INTO {TABLE_NAME}

            SELECT

                product_id,

                energy_kj,

                energy_kj_computed,

                energy_kcal,

                fat,

                saturated_fat,

                carbohydrates,

                sugars,

                starch,

                sodium,

                ingredients_text,

                ingredients_text_present,

                contains_statement_present,

                allergen_evidence_present,

                fop_threshold_exceeded,

                fop_symbol_present,

                fop_exempt_proxy,

                product_is_prepackaged_proxy,

                lc,

                lang,

                language_code

            FROM read_json_auto(?)

            """,
            [jsonl_path.as_posix()],
        )


def fetch_products(db_path: Path = DB_PATH) -> List[Dict[str, object]]:
    """Read all products from DuckDB as dictionaries."""
    with connect(db_path) as con:
        rows = con.execute(f"SELECT * FROM {TABLE_NAME}").fetchdf()
    return rows.to_dict("records")


def count_rows(db_path: Path = DB_PATH) -> int:
    with connect(db_path) as con:
        value = con.execute(f"SELECT COUNT(*) FROM {TABLE_NAME}").fetchone()
    return int(value[0] if value else 0)


def count_violations(condition_sql: str, db_path: Path = DB_PATH) -> int:
    """Count records matching a rule condition."""
    query = f"SELECT COUNT(*) FROM {TABLE_NAME} WHERE {condition_sql}"
    with connect(db_path) as con:
        value = con.execute(query).fetchone()
    return int(value[0] if value else 0)


def sample_violations(condition_sql: str, limit: int = 5, db_path: Path = DB_PATH) -> List[Dict[str, object]]:
    """Return sample violating records for dashboard drilldown."""
    query = f"""

        SELECT *

        FROM {TABLE_NAME}

        WHERE {condition_sql}

        ORDER BY product_id

        LIMIT {int(limit)}

    """
    with connect(db_path) as con:
        rows = con.execute(query).fetchdf()
    return rows.to_dict("records")