File size: 1,553 Bytes
e348dc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from sqlalchemy import create_engine, text

# 1) URL par défaut si l'env n'est pas défini
DATABASE_URL = os.getenv(
    "DATABASE_URL",
    "postgresql+psycopg2://appuser:appuser@localhost:5432/attrition"
)

engine = create_engine(DATABASE_URL, future=True, echo=False)

DDL = """
CREATE TABLE IF NOT EXISTS predictions (
  id SERIAL PRIMARY KEY,
  created_at TIMESTAMP DEFAULT NOW(),
  age INT,
  genre TEXT,
  revenu_mensuel INT,
  proba_attrition DOUBLE PRECISION,
  pred INT
);
-- index utile pour le tri par date
CREATE INDEX IF NOT EXISTS idx_predictions_created_at ON predictions(created_at);
"""

def main():
    # 2) Création la table (idempotent)
    with engine.begin() as conn:
        for stmt in DDL.strip().split(";"):
            if stmt.strip():
                conn.execute(text(stmt))

    # 3) Insérer un exemple (facultatif mais pratique)
    with engine.begin() as conn:
        conn.execute(
            text("""
                INSERT INTO predictions(age, genre, revenu_mensuel, proba_attrition, pred)
                VALUES(:age, :genre, :rev, :proba, :pred)
            """),
            {"age": 41, "genre": "F", "rev": 6000, "proba": 0.1443, "pred": 0}
        )

    # 4) Vérification
    with engine.begin() as conn:
        rows = conn.execute(text("SELECT id, created_at, age, pred FROM predictions ORDER BY id DESC LIMIT 3"))
        print("Dernières lignes :")
        for r in rows:
            print(dict(r._mapping))

    print(" Table 'predictions' prête.")

if __name__ == "__main__":
    main()