causilo-db 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
causilo_db/sql.py ADDED
@@ -0,0 +1,197 @@
1
+ """Any database SQLAlchemy can reach: read a table, predict, write the result.
2
+
3
+ from causilo_db import predict_table
4
+ result, pred = predict_table("postgresql+psycopg://...", "customers", "churn",
5
+ id_column="customer_id", out_table="customers_churn_prediction")
6
+
7
+ Works with the SQLAlchemy dialects: PostgreSQL, MySQL and MariaDB, SQL Server,
8
+ Oracle and SQLite, and through their own dialects ClickHouse, Trino, Snowflake,
9
+ BigQuery, Redshift and others. The table is read whole, so ``where`` is the
10
+ way to send part of one. The URL names the driver:
11
+ ``postgresql+psycopg://``, ``mysql+pymysql://``, ``mssql+pymssql://``,
12
+ ``oracle+oracledb://`` and so on.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import Any
18
+
19
+ import pandas as pd
20
+
21
+ from .core import CausiloDBError, Prediction, check_id_column, predict_frame
22
+
23
+
24
+ # Words Trino reserves that its SQLAlchemy dialect does not know to quote; a
25
+ # column called "trim" otherwise breaks CREATE TABLE and SELECT alike.
26
+ _TRINO_RESERVED = {
27
+ "trim", "extract", "normalize", "listagg", "skip", "uescape", "cube", "rollup", "grouping",
28
+ "localtime", "localtimestamp", "current_catalog", "current_path", "current_schema",
29
+ "json_array", "json_exists", "json_object", "json_query", "json_table", "json_value",
30
+ }
31
+
32
+
33
+ def _engine(url_or_engine: Any):
34
+ if isinstance(url_or_engine, str):
35
+ import sqlalchemy
36
+
37
+ engine = sqlalchemy.create_engine(url_or_engine)
38
+ else:
39
+ engine = url_or_engine
40
+ if engine.dialect.name == "trino":
41
+ prep = engine.dialect.identifier_preparer
42
+ prep.reserved_words = set(prep.reserved_words) | _TRINO_RESERVED
43
+ # The preparer caches each name's quoting; forget what it decided before.
44
+ getattr(prep, "_strings", {}).clear()
45
+ return engine
46
+
47
+
48
+ def read_table(engine: Any, table: str, *, schema: str | None = None, where: str | None = None,
49
+ columns: list[str] | None = None) -> pd.DataFrame:
50
+ """The table as a DataFrame. Names are quoted by the dialect, ``where`` is raw SQL."""
51
+ import sqlalchemy as sa
52
+
53
+ meta = sa.MetaData()
54
+ try:
55
+ t = sa.Table(table, meta, schema=schema, autoload_with=engine)
56
+ except sa.exc.NoSuchTableError as exc:
57
+ raise CausiloDBError(f"No table {table!r}" + (f" in schema {schema!r}" if schema else "") + ".") from exc
58
+ cols = [t.c[c] for c in columns] if columns else [t]
59
+ query = sa.select(*cols)
60
+ if where:
61
+ query = query.where(sa.text(where))
62
+ with engine.connect() as conn:
63
+ return pd.read_sql(query, conn)
64
+
65
+
66
+ def predict_table(
67
+ url_or_engine: Any,
68
+ table: str,
69
+ target: str,
70
+ *,
71
+ schema: str | None = None,
72
+ where: str | None = None,
73
+ id_column: str | None = None,
74
+ features: list[str] | None = None,
75
+ task: str | None = None,
76
+ out_table: str | None = None,
77
+ out_schema: str | None = None,
78
+ if_exists: str = "fail",
79
+ api_key: str | None = None,
80
+ endpoint: str | None = None,
81
+ client: Any = None,
82
+ ) -> tuple[pd.DataFrame, Prediction]:
83
+ """Predict the blank cells of ``target`` in ``table``.
84
+
85
+ The result has ``id_column`` (when given; otherwise ``row_number``) and the
86
+ prediction columns. With ``out_table`` it is also written to the database;
87
+ ``if_exists`` is passed to pandas (``fail``, ``replace`` or ``append``).
88
+ """
89
+ if if_exists not in ("fail", "replace", "append"):
90
+ raise CausiloDBError(f"if_exists must be 'fail', 'replace' or 'append', not {if_exists!r}.")
91
+ check_id_column(id_column, target)
92
+ if out_table and out_table == table and (out_schema or None) == (schema or None):
93
+ raise CausiloDBError("out_table is the table being read; write the result to another table.")
94
+ engine = _engine(url_or_engine)
95
+ df = read_table(engine, table, schema=schema, where=where)
96
+ if df.empty:
97
+ raise CausiloDBError(f"No rows were read from {table!r}" + (" with that condition." if where else "."))
98
+ if id_column is not None and id_column not in df.columns:
99
+ raise CausiloDBError(f"No column named {id_column!r}.")
100
+ if out_table and if_exists == "fail":
101
+ import sqlalchemy as sa
102
+
103
+ # Refuse before the prediction is paid for, not after.
104
+ if sa.inspect(engine).has_table(out_table, schema=out_schema):
105
+ name = f"{out_schema}.{out_table}" if out_schema else out_table
106
+ raise CausiloDBError(f"Table {name} already exists; pass if_exists='replace' or 'append'.")
107
+ pred = predict_frame(df, target, features=features, exclude=[id_column] if id_column else None,
108
+ task=task, api_key=api_key, endpoint=endpoint, client=client)
109
+ result = pred.frame
110
+ if id_column is not None:
111
+ ids = df[id_column].reset_index(drop=True)
112
+ result = result.copy()
113
+ result.insert(0, id_column, ids.iloc[result["row_number"]].to_numpy())
114
+ result = result.drop(columns=["row_number"])
115
+ if out_table:
116
+ try:
117
+ write_table(result, engine, out_table, schema=out_schema, if_exists=if_exists)
118
+ except Exception as exc:
119
+ err = CausiloDBError(f"The prediction was made but could not be written to {out_table}: {exc}")
120
+ err.result, err.prediction = result, pred
121
+ raise err from exc
122
+ return result, pred
123
+
124
+
125
+ def _clickhouse_type(col: pd.Series) -> str:
126
+ if pd.api.types.is_bool_dtype(col):
127
+ return "Nullable(UInt8)"
128
+ if pd.api.types.is_integer_dtype(col):
129
+ return "Nullable(Int64)"
130
+ if pd.api.types.is_float_dtype(col):
131
+ return "Nullable(Float64)"
132
+ if pd.api.types.is_datetime64_any_dtype(col):
133
+ return "Nullable(DateTime64(6))"
134
+ return "Nullable(String)"
135
+
136
+
137
+ def write_table(df: pd.DataFrame, engine: Any, table: str, *, schema: str | None = None,
138
+ if_exists: str = "fail") -> None:
139
+ """Write ``df`` as a table, smoothing over the dialects pandas cannot write to as is."""
140
+ import sqlalchemy as sa
141
+
142
+ if if_exists not in ("fail", "replace", "append"):
143
+ raise CausiloDBError(f"if_exists must be 'fail', 'replace' or 'append', not {if_exists!r}.")
144
+ engine = _engine(engine)
145
+ dialect = engine.dialect.name
146
+ if dialect == "clickhouse":
147
+ # ClickHouse needs a table engine, which pandas has no way to name.
148
+ name = f"{schema}.{table}" if schema else table
149
+ quoted = ".".join("`" + p.replace("`", "``") + "`" for p in ([schema, table] if schema else [table]))
150
+ with engine.begin() as con:
151
+ exists = sa.inspect(con).has_table(table, schema=schema)
152
+ if exists and if_exists == "fail":
153
+ raise CausiloDBError(f"Table {name} already exists; pass if_exists='replace' or 'append'.")
154
+ if exists and if_exists == "replace":
155
+ con.execute(sa.text(f"DROP TABLE {quoted}"))
156
+ exists = False
157
+ if not exists:
158
+ cols = ", ".join("`" + str(c).replace("`", "``") + f"` {_clickhouse_type(df[c])}" for c in df.columns)
159
+ con.execute(sa.text(f"CREATE TABLE {quoted} ({cols}) ENGINE = MergeTree ORDER BY tuple()"))
160
+ df.to_sql(table, engine, schema=schema, if_exists="append", index=False)
161
+ return
162
+ dtype = None
163
+ if dialect == "redshift":
164
+ # pandas asks for TEXT, which Redshift makes VARCHAR(256) bytes.
165
+ dtype = {c: sa.types.VARCHAR(65535) for c in df.columns
166
+ if pd.api.types.is_object_dtype(df[c]) or pd.api.types.is_string_dtype(df[c])}
167
+ if dialect == "oracle":
168
+ # pandas asks Oracle for FLOAT(53), which SQLAlchemy refuses, and for CLOB for text.
169
+ from sqlalchemy.dialects import oracle
170
+
171
+ dtype = {}
172
+ for c in df.columns:
173
+ if pd.api.types.is_float_dtype(df[c]):
174
+ dtype[c] = oracle.BINARY_DOUBLE()
175
+ elif pd.api.types.is_object_dtype(df[c]) or pd.api.types.is_string_dtype(df[c]):
176
+ lengths = df[c].dropna().astype(str).str.len()
177
+ longest = int(lengths.max()) if len(lengths) else 1
178
+ dtype[c] = sa.String(min(4000, max(1, longest)))
179
+ # Redshift and BigQuery run each single-row INSERT as its own statement (on
180
+ # BigQuery a job of its own); a multi-row INSERT per batch costs about one.
181
+ # A multi-row INSERT binds rows x columns parameters, and BigQuery takes at
182
+ # most 10,000 in one query; size the batch by the width of the table.
183
+ limits = {"redshift": (1000, 30_000), "bigquery": (500, 9_000)}
184
+ method, chunksize = None, None
185
+ if dialect in limits:
186
+ rows, params = limits[dialect]
187
+ method, chunksize = "multi", max(1, min(rows, params // max(1, len(df.columns))))
188
+ if dialect == "redshift" and if_exists == "replace":
189
+ # pandas checks for a view before replacing, and the Redshift dialect asks
190
+ # pg_class for a column Redshift does not have; drop the table ourselves.
191
+ prep = engine.dialect.identifier_preparer
192
+ name = prep.quote(table) if not schema else f"{prep.quote_schema(schema)}.{prep.quote(table)}"
193
+ with engine.begin() as con:
194
+ con.execute(sa.text(f"DROP TABLE IF EXISTS {name}"))
195
+ if_exists = "append"
196
+ df.to_sql(table, engine, schema=schema, if_exists=if_exists, index=False, dtype=dtype,
197
+ method=method, chunksize=chunksize)