kumoai 2.13.0.dev202512041731__cp310-cp310-win_amd64.whl → 2.15.0.dev202601141731__cp310-cp310-win_amd64.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.
Files changed (56) hide show
  1. kumoai/__init__.py +23 -26
  2. kumoai/_version.py +1 -1
  3. kumoai/client/client.py +6 -0
  4. kumoai/client/jobs.py +26 -0
  5. kumoai/client/pquery.py +6 -2
  6. kumoai/connector/utils.py +21 -7
  7. kumoai/experimental/rfm/__init__.py +51 -24
  8. kumoai/experimental/rfm/authenticate.py +3 -4
  9. kumoai/experimental/rfm/backend/local/__init__.py +4 -0
  10. kumoai/experimental/rfm/{local_graph_store.py → backend/local/graph_store.py} +62 -110
  11. kumoai/experimental/rfm/backend/local/sampler.py +312 -0
  12. kumoai/experimental/rfm/backend/local/table.py +35 -31
  13. kumoai/experimental/rfm/backend/snow/__init__.py +2 -0
  14. kumoai/experimental/rfm/backend/snow/sampler.py +407 -0
  15. kumoai/experimental/rfm/backend/snow/table.py +178 -50
  16. kumoai/experimental/rfm/backend/sqlite/__init__.py +4 -2
  17. kumoai/experimental/rfm/backend/sqlite/sampler.py +456 -0
  18. kumoai/experimental/rfm/backend/sqlite/table.py +131 -48
  19. kumoai/experimental/rfm/base/__init__.py +22 -4
  20. kumoai/experimental/rfm/base/column.py +96 -10
  21. kumoai/experimental/rfm/base/expression.py +44 -0
  22. kumoai/experimental/rfm/base/mapper.py +69 -0
  23. kumoai/experimental/rfm/base/sampler.py +696 -47
  24. kumoai/experimental/rfm/base/source.py +2 -1
  25. kumoai/experimental/rfm/base/sql_sampler.py +385 -0
  26. kumoai/experimental/rfm/base/table.py +384 -207
  27. kumoai/experimental/rfm/base/utils.py +36 -0
  28. kumoai/experimental/rfm/graph.py +359 -187
  29. kumoai/experimental/rfm/infer/__init__.py +6 -4
  30. kumoai/experimental/rfm/infer/dtype.py +10 -5
  31. kumoai/experimental/rfm/infer/multicategorical.py +1 -1
  32. kumoai/experimental/rfm/infer/pkey.py +4 -2
  33. kumoai/experimental/rfm/infer/stype.py +35 -0
  34. kumoai/experimental/rfm/infer/time_col.py +5 -4
  35. kumoai/experimental/rfm/pquery/executor.py +27 -27
  36. kumoai/experimental/rfm/pquery/pandas_executor.py +30 -32
  37. kumoai/experimental/rfm/relbench.py +76 -0
  38. kumoai/experimental/rfm/rfm.py +770 -467
  39. kumoai/experimental/rfm/sagemaker.py +4 -4
  40. kumoai/experimental/rfm/task_table.py +292 -0
  41. kumoai/kumolib.cp310-win_amd64.pyd +0 -0
  42. kumoai/pquery/predictive_query.py +10 -6
  43. kumoai/pquery/training_table.py +16 -2
  44. kumoai/testing/snow.py +50 -0
  45. kumoai/trainer/distilled_trainer.py +175 -0
  46. kumoai/utils/__init__.py +3 -2
  47. kumoai/utils/display.py +87 -0
  48. kumoai/utils/progress_logger.py +192 -13
  49. kumoai/utils/sql.py +3 -0
  50. {kumoai-2.13.0.dev202512041731.dist-info → kumoai-2.15.0.dev202601141731.dist-info}/METADATA +3 -2
  51. {kumoai-2.13.0.dev202512041731.dist-info → kumoai-2.15.0.dev202601141731.dist-info}/RECORD +54 -42
  52. kumoai/experimental/rfm/local_graph_sampler.py +0 -223
  53. kumoai/experimental/rfm/local_pquery_driver.py +0 -689
  54. {kumoai-2.13.0.dev202512041731.dist-info → kumoai-2.15.0.dev202601141731.dist-info}/WHEEL +0 -0
  55. {kumoai-2.13.0.dev202512041731.dist-info → kumoai-2.15.0.dev202601141731.dist-info}/licenses/LICENSE +0 -0
  56. {kumoai-2.13.0.dev202512041731.dist-info → kumoai-2.15.0.dev202601141731.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,456 @@
1
+ import warnings
2
+ from collections import defaultdict
3
+ from typing import TYPE_CHECKING
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ import pyarrow as pa
8
+ from kumoapi.pquery import ValidatedPredictiveQuery
9
+
10
+ from kumoai.experimental.rfm.backend.sqlite import SQLiteTable
11
+ from kumoai.experimental.rfm.base import SQLSampler, Table
12
+ from kumoai.experimental.rfm.pquery import PQueryPandasExecutor
13
+ from kumoai.utils import ProgressLogger, quote_ident
14
+
15
+ if TYPE_CHECKING:
16
+ from kumoai.experimental.rfm import Graph
17
+
18
+
19
+ class SQLiteSampler(SQLSampler):
20
+ def __init__(
21
+ self,
22
+ graph: 'Graph',
23
+ verbose: bool | ProgressLogger = True,
24
+ optimize: bool = False,
25
+ ) -> None:
26
+ super().__init__(graph=graph, verbose=verbose)
27
+
28
+ for table in graph.tables.values():
29
+ assert isinstance(table, SQLiteTable)
30
+ self._connection = table._connection
31
+
32
+ if optimize:
33
+ with self._connection.cursor() as cursor:
34
+ cursor.execute("PRAGMA temp_store = MEMORY")
35
+ cursor.execute("PRAGMA cache_size = -2000000") # 2 GB
36
+
37
+ # Collect database indices for speeding sampling:
38
+ index_dict: dict[str, set[tuple[str, ...]]] = defaultdict(set)
39
+ for table_name, primary_key in self.primary_key_dict.items():
40
+ source_table = self.source_table_dict[table_name]
41
+ if primary_key not in source_table:
42
+ continue # No physical column.
43
+ if source_table[primary_key].is_unique_key:
44
+ continue
45
+ index_dict[table_name].add((primary_key, ))
46
+ for src_table_name, foreign_key, _ in graph.edges:
47
+ source_table = self.source_table_dict[src_table_name]
48
+ if foreign_key not in source_table:
49
+ continue # No physical column.
50
+ if source_table[foreign_key].is_unique_key:
51
+ continue
52
+ time_column = self.time_column_dict.get(src_table_name)
53
+ if time_column is not None and time_column in source_table:
54
+ index_dict[src_table_name].add((foreign_key, time_column))
55
+ else:
56
+ index_dict[src_table_name].add((foreign_key, ))
57
+
58
+ # Only maintain missing indices:
59
+ with self._connection.cursor() as cursor:
60
+ for table_name in list(index_dict.keys()):
61
+ indices = index_dict[table_name]
62
+ source_name = self.source_name_dict[table_name]
63
+ sql = f"PRAGMA index_list({source_name})"
64
+ cursor.execute(sql)
65
+ for _, index_name, *_ in cursor.fetchall():
66
+ sql = f"PRAGMA index_info({quote_ident(index_name)})"
67
+ cursor.execute(sql)
68
+ # Fetch index information and sort by `seqno`:
69
+ index_info = tuple(info[2] for info in sorted(
70
+ cursor.fetchall(), key=lambda x: x[0]))
71
+ # Remove all indices in case primary index already exists:
72
+ for index in list(indices):
73
+ if index_info[0] == index[0]:
74
+ indices.discard(index)
75
+ if len(indices) == 0:
76
+ del index_dict[table_name]
77
+
78
+ if optimize and len(index_dict) > 0:
79
+ if not isinstance(verbose, ProgressLogger):
80
+ verbose = ProgressLogger.default(
81
+ msg="Optimizing SQLite database",
82
+ verbose=verbose,
83
+ )
84
+
85
+ with verbose as logger, self._connection.cursor() as cursor:
86
+ for table_name, indices in index_dict.items():
87
+ for index in indices:
88
+ name = f"kumo_index_{table_name}_{'_'.join(index)}"
89
+ name = quote_ident(name)
90
+ columns = ', '.join(quote_ident(v) for v in index)
91
+ columns += ' DESC' if len(index) > 1 else ''
92
+ source_name = self.source_name_dict[table_name]
93
+ sql = (f"CREATE INDEX IF NOT EXISTS {name}\n"
94
+ f"ON {source_name}({columns})")
95
+ cursor.execute(sql)
96
+ self._connection.commit()
97
+ if len(index) > 1:
98
+ logger.log(f"Created index on {index} in table "
99
+ f"'{table_name}'")
100
+ else:
101
+ logger.log(f"Created index on '{index[0]}' in "
102
+ f"table '{table_name}'")
103
+
104
+ elif len(index_dict) > 0:
105
+ num = sum(len(indices) for indices in index_dict.values())
106
+ index_repr = '1 index' if num == 1 else f'{num} indices'
107
+ num = len(index_dict)
108
+ table_repr = '1 table' if num == 1 else f'{num} tables'
109
+ warnings.warn(f"Missing {index_repr} in {table_repr} for optimal "
110
+ f"database querying. For improving runtime, we "
111
+ f"strongly suggest to create indices for primary "
112
+ f"and foreign keys, e.g., automatically by "
113
+ f"instantiating KumoRFM via "
114
+ f"`KumoRFM(graph, optimize=True)`.")
115
+
116
+ def _get_min_max_time_dict(
117
+ self,
118
+ table_names: list[str],
119
+ ) -> dict[str, tuple[pd.Timestamp, pd.Timestamp]]:
120
+ selects: list[str] = []
121
+ for table_name in table_names:
122
+ column = self.time_column_dict[table_name]
123
+ column_ref = self.table_column_ref_dict[table_name][column]
124
+ ident = quote_ident(table_name, char="'")
125
+ select = (f"SELECT\n"
126
+ f" {ident} as table_name,\n"
127
+ f" MIN({column_ref}) as min_date,\n"
128
+ f" MAX({column_ref}) as max_date\n"
129
+ f"FROM {self.source_name_dict[table_name]}")
130
+ selects.append(select)
131
+ sql = "\nUNION ALL\n".join(selects)
132
+
133
+ out_dict: dict[str, tuple[pd.Timestamp, pd.Timestamp]] = {}
134
+ with self._connection.cursor() as cursor:
135
+ cursor.execute(sql)
136
+ for table_name, _min, _max in cursor.fetchall():
137
+ out_dict[table_name] = (
138
+ pd.Timestamp.max if _min is None else pd.Timestamp(_min),
139
+ pd.Timestamp.min if _max is None else pd.Timestamp(_max),
140
+ )
141
+
142
+ return out_dict
143
+
144
+ def _sample_entity_table(
145
+ self,
146
+ table_name: str,
147
+ columns: set[str],
148
+ num_rows: int,
149
+ random_seed: int | None = None,
150
+ ) -> pd.DataFrame:
151
+ # NOTE SQLite does not natively support passing a `random_seed`.
152
+
153
+ source_table = self.source_table_dict[table_name]
154
+ filters: list[str] = []
155
+
156
+ key = self.primary_key_dict[table_name]
157
+ if key not in source_table or source_table[key].is_nullable:
158
+ key_ref = self.table_column_ref_dict[table_name][key]
159
+ filters.append(f" {key_ref} IS NOT NULL")
160
+
161
+ column = self.time_column_dict.get(table_name)
162
+ if column is None:
163
+ pass
164
+ elif column not in source_table or source_table[column].is_nullable:
165
+ column_ref = self.table_column_ref_dict[table_name][column]
166
+ filters.append(f" {column_ref} IS NOT NULL")
167
+
168
+ # TODO Make this query more efficient - it does full table scan.
169
+ projections = [
170
+ self.table_column_proj_dict[table_name][column]
171
+ for column in columns
172
+ ]
173
+ sql = (f"SELECT {', '.join(projections)}\n"
174
+ f"FROM {self.source_name_dict[table_name]}")
175
+ if len(filters) > 0:
176
+ sql += f"\nWHERE{' AND'.join(filters)}"
177
+ sql += f"\nORDER BY RANDOM() LIMIT {num_rows}"
178
+
179
+ with self._connection.cursor() as cursor:
180
+ # NOTE This may return duplicate primary keys. This is okay.
181
+ cursor.execute(sql)
182
+ table = cursor.fetch_arrow_table()
183
+
184
+ return Table._sanitize(
185
+ df=table.to_pandas(types_mapper=pd.ArrowDtype),
186
+ dtype_dict=self.table_dtype_dict[table_name],
187
+ stype_dict=self.table_stype_dict[table_name],
188
+ )
189
+
190
+ def _sample_target(
191
+ self,
192
+ query: ValidatedPredictiveQuery,
193
+ entity_df: pd.DataFrame,
194
+ train_index: np.ndarray,
195
+ train_time: pd.Series,
196
+ num_train_examples: int,
197
+ test_index: np.ndarray,
198
+ test_time: pd.Series,
199
+ num_test_examples: int,
200
+ columns_dict: dict[str, set[str]],
201
+ time_offset_dict: dict[
202
+ tuple[str, str, str],
203
+ tuple[pd.DateOffset | None, pd.DateOffset],
204
+ ],
205
+ ) -> tuple[pd.Series, np.ndarray, pd.Series, np.ndarray]:
206
+ train_y, train_mask = self._sample_target_set(
207
+ query=query,
208
+ entity_df=entity_df,
209
+ index=train_index,
210
+ anchor_time=train_time,
211
+ num_examples=num_train_examples,
212
+ columns_dict=columns_dict,
213
+ time_offset_dict=time_offset_dict,
214
+ )
215
+
216
+ test_y, test_mask = self._sample_target_set(
217
+ query=query,
218
+ entity_df=entity_df,
219
+ index=test_index,
220
+ anchor_time=test_time,
221
+ num_examples=num_test_examples,
222
+ columns_dict=columns_dict,
223
+ time_offset_dict=time_offset_dict,
224
+ )
225
+
226
+ return train_y, train_mask, test_y, test_mask
227
+
228
+ def _by_pkey(
229
+ self,
230
+ table_name: str,
231
+ index: pd.Series,
232
+ columns: set[str],
233
+ ) -> tuple[pd.DataFrame, np.ndarray]:
234
+ source_table = self.source_table_dict[table_name]
235
+ key = self.primary_key_dict[table_name]
236
+ key_ref = self.table_column_ref_dict[table_name][key]
237
+ projections = [
238
+ self.table_column_proj_dict[table_name][column]
239
+ for column in columns
240
+ ]
241
+
242
+ tmp = pa.table([pa.array(index)], names=['__kumo_id__'])
243
+ tmp_name = f'tmp_{table_name}_{key}_{id(tmp)}'
244
+
245
+ sql = (f"SELECT "
246
+ f"tmp.rowid - 1 as __kumo_batch__, "
247
+ f"{', '.join(projections)}\n"
248
+ f"FROM {quote_ident(tmp_name)} tmp\n"
249
+ f"JOIN {self.source_name_dict[table_name]} ent\n")
250
+ if key in source_table and source_table[key].is_unique_key:
251
+ sql += (f" ON {key_ref} = tmp.__kumo_id__")
252
+ else:
253
+ sql += (f" ON ent.rowid = (\n"
254
+ f" SELECT rowid\n"
255
+ f" FROM {self.source_name_dict[table_name]}\n"
256
+ f" WHERE {key_ref} == tmp.__kumo_id__\n"
257
+ f" LIMIT 1\n"
258
+ f")")
259
+
260
+ with self._connection.cursor() as cursor:
261
+ cursor.adbc_ingest(tmp_name, tmp, mode='replace')
262
+ cursor.execute(sql)
263
+ table = cursor.fetch_arrow_table()
264
+
265
+ batch = table['__kumo_batch__'].to_numpy()
266
+ batch_index = table.schema.get_field_index('__kumo_batch__')
267
+ table = table.remove_column(batch_index)
268
+
269
+ return Table._sanitize(
270
+ df=table.to_pandas(),
271
+ dtype_dict=self.table_dtype_dict[table_name],
272
+ stype_dict=self.table_stype_dict[table_name],
273
+ ), batch
274
+
275
+ def _by_fkey(
276
+ self,
277
+ table_name: str,
278
+ foreign_key: str,
279
+ index: pd.Series,
280
+ num_neighbors: int,
281
+ anchor_time: pd.Series | None,
282
+ columns: set[str],
283
+ ) -> tuple[pd.DataFrame, np.ndarray]:
284
+ time_column = self.time_column_dict.get(table_name)
285
+
286
+ # NOTE SQLite does not have a native datetime format. Currently, we
287
+ # assume timestamps are given as `TEXT` in `ISO-8601 UTC`:
288
+ tmp = pa.table([pa.array(index)], names=['__kumo_id__'])
289
+ if time_column is not None and anchor_time is not None:
290
+ anchor_time = anchor_time.dt.strftime("%Y-%m-%d %H:%M:%S")
291
+ tmp = tmp.append_column('__kumo_time__', pa.array(anchor_time))
292
+ tmp_name = f'tmp_{table_name}_{foreign_key}_{id(tmp)}'
293
+
294
+ key_ref = self.table_column_ref_dict[table_name][foreign_key]
295
+ projections = [
296
+ self.table_column_proj_dict[table_name][column]
297
+ for column in columns
298
+ ]
299
+ sql = (f"SELECT "
300
+ f"tmp.rowid - 1 as __kumo_batch__, "
301
+ f"{', '.join(projections)}\n"
302
+ f"FROM {quote_ident(tmp_name)} tmp\n"
303
+ f"JOIN {self.source_name_dict[table_name]} fact\n"
304
+ f"ON fact.rowid IN (\n"
305
+ f" SELECT rowid\n"
306
+ f" FROM {self.source_name_dict[table_name]}\n"
307
+ f" WHERE {key_ref} = tmp.__kumo_id__\n")
308
+ if time_column is not None and anchor_time is not None:
309
+ time_ref = self.table_column_ref_dict[table_name][time_column]
310
+ sql += f" AND {time_ref} <= tmp.__kumo_time__\n"
311
+ if time_column is not None:
312
+ time_ref = self.table_column_ref_dict[table_name][time_column]
313
+ sql += f" ORDER BY {time_ref} DESC\n"
314
+ sql += (f" LIMIT {num_neighbors}\n"
315
+ f")")
316
+
317
+ with self._connection.cursor() as cursor:
318
+ cursor.adbc_ingest(tmp_name, tmp, mode='replace')
319
+ cursor.execute(sql)
320
+ table = cursor.fetch_arrow_table()
321
+
322
+ batch = table['__kumo_batch__'].to_numpy()
323
+ batch_index = table.schema.get_field_index('__kumo_batch__')
324
+ table = table.remove_column(batch_index)
325
+
326
+ return Table._sanitize(
327
+ df=table.to_pandas(),
328
+ dtype_dict=self.table_dtype_dict[table_name],
329
+ stype_dict=self.table_stype_dict[table_name],
330
+ ), batch
331
+
332
+ # Helper Methods ##########################################################
333
+
334
+ def _by_time(
335
+ self,
336
+ table_name: str,
337
+ foreign_key: str,
338
+ index: pd.Series,
339
+ anchor_time: pd.Series,
340
+ min_offset: pd.DateOffset | None,
341
+ max_offset: pd.DateOffset,
342
+ columns: set[str],
343
+ ) -> tuple[pd.DataFrame, np.ndarray]:
344
+ time_column = self.time_column_dict[table_name]
345
+
346
+ # NOTE SQLite does not have a native datetime format. Currently, we
347
+ # assume timestamps are given as `TEXT` in `ISO-8601 UTC`:
348
+ tmp = pa.table([pa.array(index)], names=['__kumo_id__'])
349
+ end_time = anchor_time + max_offset
350
+ end_time = end_time.dt.strftime("%Y-%m-%d %H:%M:%S")
351
+ tmp = tmp.append_column('__kumo_end__', pa.array(end_time))
352
+ if min_offset is not None:
353
+ start_time = anchor_time + min_offset
354
+ start_time = start_time.dt.strftime("%Y-%m-%d %H:%M:%S")
355
+ tmp = tmp.append_column('__kumo_start__', pa.array(start_time))
356
+ tmp_name = f'tmp_{table_name}_{foreign_key}_{id(tmp)}'
357
+
358
+ key_ref = self.table_column_ref_dict[table_name][foreign_key]
359
+ time_ref = self.table_column_ref_dict[table_name][time_column]
360
+ projections = [
361
+ self.table_column_proj_dict[table_name][column]
362
+ for column in columns
363
+ ]
364
+ sql = (f"SELECT "
365
+ f"tmp.rowid - 1 as __kumo_batch__, "
366
+ f"{', '.join(projections)}\n"
367
+ f"FROM {quote_ident(tmp_name)} tmp\n"
368
+ f"JOIN {self.source_name_dict[table_name]}\n"
369
+ f" ON {key_ref} = tmp.__kumo_id__\n"
370
+ f" AND {time_ref} <= tmp.__kumo_end__")
371
+ if min_offset is not None:
372
+ sql += f"\n AND {time_ref} > tmp.__kumo_start__"
373
+
374
+ with self._connection.cursor() as cursor:
375
+ cursor.adbc_ingest(tmp_name, tmp, mode='replace')
376
+ cursor.execute(sql)
377
+ table = cursor.fetch_arrow_table()
378
+
379
+ batch = table['__kumo_batch__'].to_numpy()
380
+ batch_index = table.schema.get_field_index('__kumo_batch__')
381
+ table = table.remove_column(batch_index)
382
+
383
+ return Table._sanitize(
384
+ df=table.to_pandas(types_mapper=pd.ArrowDtype),
385
+ dtype_dict=self.table_dtype_dict[table_name],
386
+ stype_dict=self.table_stype_dict[table_name],
387
+ ), batch
388
+
389
+ def _sample_target_set(
390
+ self,
391
+ query: ValidatedPredictiveQuery,
392
+ entity_df: pd.DataFrame,
393
+ index: np.ndarray,
394
+ anchor_time: pd.Series,
395
+ num_examples: int,
396
+ columns_dict: dict[str, set[str]],
397
+ time_offset_dict: dict[
398
+ tuple[str, str, str],
399
+ tuple[pd.DateOffset | None, pd.DateOffset],
400
+ ],
401
+ batch_size: int = 10_000,
402
+ ) -> tuple[pd.Series, np.ndarray]:
403
+
404
+ count = 0
405
+ ys: list[pd.Series] = []
406
+ mask = np.full(len(index), False, dtype=bool)
407
+ for start in range(0, len(index), batch_size):
408
+ df = entity_df.iloc[index[start:start + batch_size]]
409
+ time = anchor_time.iloc[start:start + batch_size]
410
+
411
+ feat_dict: dict[str, pd.DataFrame] = {query.entity_table: df}
412
+ time_dict: dict[str, pd.Series] = {}
413
+ time_column = self.time_column_dict.get(query.entity_table)
414
+ if time_column in columns_dict[query.entity_table]:
415
+ time_dict[query.entity_table] = df[time_column]
416
+ batch_dict: dict[str, np.ndarray] = {
417
+ query.entity_table: np.arange(len(df)),
418
+ }
419
+ for edge_type, (_min, _max) in time_offset_dict.items():
420
+ table_name, foreign_key, _ = edge_type
421
+ feat_dict[table_name], batch_dict[table_name] = self._by_time(
422
+ table_name=table_name,
423
+ foreign_key=foreign_key,
424
+ index=df[self.primary_key_dict[query.entity_table]],
425
+ anchor_time=time,
426
+ min_offset=_min,
427
+ max_offset=_max,
428
+ columns=columns_dict[table_name],
429
+ )
430
+ time_column = self.time_column_dict.get(table_name)
431
+ if time_column in columns_dict[table_name]:
432
+ time_dict[table_name] = feat_dict[table_name][time_column]
433
+
434
+ y, _mask = PQueryPandasExecutor().execute(
435
+ query=query,
436
+ feat_dict=feat_dict,
437
+ time_dict=time_dict,
438
+ batch_dict=batch_dict,
439
+ anchor_time=time,
440
+ num_forecasts=query.num_forecasts,
441
+ )
442
+ ys.append(y)
443
+ mask[start:start + batch_size] = _mask
444
+
445
+ count += len(y)
446
+ if count >= num_examples:
447
+ break
448
+
449
+ if len(ys) == 0:
450
+ y = pd.Series([], dtype=float)
451
+ elif len(ys) == 1:
452
+ y = ys[0]
453
+ else:
454
+ y = pd.concat(ys, axis=0, ignore_index=True)
455
+
456
+ return y, mask
@@ -1,13 +1,22 @@
1
1
  import re
2
- import warnings
3
- from typing import List, Optional, Sequence
2
+ from collections import Counter
3
+ from collections.abc import Sequence
4
+ from typing import cast
4
5
 
5
6
  import pandas as pd
7
+ from kumoapi.model_plan import MissingType
6
8
  from kumoapi.typing import Dtype
7
9
 
8
10
  from kumoai.experimental.rfm.backend.sqlite import Connection
9
- from kumoai.experimental.rfm.base import SourceColumn, SourceForeignKey, Table
10
- from kumoai.experimental.rfm.infer import infer_dtype
11
+ from kumoai.experimental.rfm.base import (
12
+ ColumnSpec,
13
+ ColumnSpecType,
14
+ DataBackend,
15
+ SourceColumn,
16
+ SourceForeignKey,
17
+ Table,
18
+ )
19
+ from kumoai.utils import quote_ident
11
20
 
12
21
 
13
22
  class SQLiteTable(Table):
@@ -16,6 +25,8 @@ class SQLiteTable(Table):
16
25
  Args:
17
26
  connection: The connection to a :class:`sqlite` database.
18
27
  name: The name of this table.
28
+ source_name: The source name of this table. If set to ``None``,
29
+ ``name`` is being used.
19
30
  columns: The selected columns of this table.
20
31
  primary_key: The name of the primary key of this table, if it exists.
21
32
  time_column: The name of the time column of this table, if it exists.
@@ -26,76 +37,148 @@ class SQLiteTable(Table):
26
37
  self,
27
38
  connection: Connection,
28
39
  name: str,
29
- columns: Optional[Sequence[str]] = None,
30
- primary_key: Optional[str] = None,
31
- time_column: Optional[str] = None,
32
- end_time_column: Optional[str] = None,
40
+ source_name: str | None = None,
41
+ columns: Sequence[ColumnSpecType] | None = None,
42
+ primary_key: MissingType | str | None = MissingType.VALUE,
43
+ time_column: str | None = None,
44
+ end_time_column: str | None = None,
33
45
  ) -> None:
34
46
 
35
47
  self._connection = connection
36
48
 
37
49
  super().__init__(
38
50
  name=name,
51
+ source_name=source_name,
39
52
  columns=columns,
40
53
  primary_key=primary_key,
41
54
  time_column=time_column,
42
55
  end_time_column=end_time_column,
43
56
  )
44
57
 
45
- def _get_source_columns(self) -> List[SourceColumn]:
46
- source_columns: List[SourceColumn] = []
58
+ @property
59
+ def backend(self) -> DataBackend:
60
+ return cast(DataBackend, DataBackend.SQLITE)
61
+
62
+ def _get_source_columns(self) -> list[SourceColumn]:
63
+ source_columns: list[SourceColumn] = []
47
64
  with self._connection.cursor() as cursor:
48
- cursor.execute(f"PRAGMA table_info({self.name})")
49
- rows = cursor.fetchall()
65
+ sql = f"PRAGMA table_info({self._quoted_source_name})"
66
+ cursor.execute(sql)
67
+ columns = cursor.fetchall()
68
+
69
+ if len(columns) == 0:
70
+ raise ValueError(f"Table '{self.source_name}' does not exist "
71
+ f"in the SQLite database")
72
+
73
+ unique_keys: set[str] = set()
74
+ sql = f"PRAGMA index_list({self._quoted_source_name})"
75
+ cursor.execute(sql)
76
+ for _, index_name, is_unique, *_ in cursor.fetchall():
77
+ if bool(is_unique):
78
+ sql = f"PRAGMA index_info({quote_ident(index_name)})"
79
+ cursor.execute(sql)
80
+ index = cursor.fetchall()
81
+ if len(index) == 1:
82
+ unique_keys.add(index[0][2])
50
83
 
51
- if len(rows) == 0:
52
- raise ValueError(f"Table '{self.name}' does not exist")
53
-
54
- for _, column, type, _, _, is_pkey in rows:
55
- # Determine column affinity:
56
- type = type.strip().upper()
57
- if re.search('INT', type):
58
- dtype = Dtype.int
59
- elif re.search('TEXT|CHAR|CLOB', type):
60
- dtype = Dtype.string
61
- elif re.search('REAL|FLOA|DOUB', type):
62
- dtype = Dtype.float
63
- else: # NUMERIC affinity.
64
- ser = self._sample_df[column]
65
- try:
66
- dtype = infer_dtype(ser)
67
- except Exception:
68
- warnings.warn(
69
- f"Data type inference for column '{column}' in "
70
- f"table '{self.name}' failed. Consider changing "
71
- f"the data type of the column to use it within "
72
- f"this table.")
73
- continue
84
+ # Special SQLite case that creates a rowid alias for
85
+ # `INTEGER PRIMARY KEY` annotated columns:
86
+ rowid_candidates = [
87
+ column for _, column, dtype, _, _, is_pkey in columns
88
+ if bool(is_pkey) and dtype.strip().upper() == 'INTEGER'
89
+ ]
90
+ if len(rowid_candidates) == 1:
91
+ unique_keys.add(rowid_candidates[0])
74
92
 
93
+ for _, column, dtype, notnull, _, is_pkey in columns:
75
94
  source_column = SourceColumn(
76
95
  name=column,
77
- dtype=dtype,
96
+ dtype=self._to_dtype(dtype),
78
97
  is_primary_key=bool(is_pkey),
79
- is_unique_key=False,
98
+ is_unique_key=column in unique_keys,
99
+ is_nullable=not bool(is_pkey) and not bool(notnull),
80
100
  )
81
101
  source_columns.append(source_column)
82
102
 
83
103
  return source_columns
84
104
 
85
- def _get_source_foreign_keys(self) -> List[SourceForeignKey]:
86
- source_fkeys: List[SourceForeignKey] = []
105
+ def _get_source_foreign_keys(self) -> list[SourceForeignKey]:
106
+ source_foreign_keys: list[SourceForeignKey] = []
87
107
  with self._connection.cursor() as cursor:
88
- cursor.execute(f"PRAGMA foreign_key_list({self.name})")
89
- for _, _, dst_table, fkey, pkey, _, _, _ in cursor.fetchall():
90
- source_fkeys.append(SourceForeignKey(fkey, dst_table, pkey))
91
- return source_fkeys
108
+ sql = f"PRAGMA foreign_key_list({self._quoted_source_name})"
109
+ cursor.execute(sql)
110
+ rows = cursor.fetchall()
111
+ counts = Counter(row[0] for row in rows)
112
+ for idx, _, dst_table, foreign_key, primary_key, *_ in rows:
113
+ if counts[idx] == 1:
114
+ source_foreign_key = SourceForeignKey(
115
+ name=foreign_key,
116
+ dst_table=dst_table,
117
+ primary_key=primary_key,
118
+ )
119
+ source_foreign_keys.append(source_foreign_key)
120
+ return source_foreign_keys
92
121
 
93
- def _get_sample_df(self) -> pd.DataFrame:
122
+ def _get_source_sample_df(self) -> pd.DataFrame:
94
123
  with self._connection.cursor() as cursor:
95
- cursor.execute(f"SELECT * FROM {self.name} "
96
- f"ORDER BY rowid LIMIT 1000")
124
+ columns = [quote_ident(col) for col in self._source_column_dict]
125
+ sql = (f"SELECT {', '.join(columns)} "
126
+ f"FROM {self._quoted_source_name} "
127
+ f"ORDER BY rowid "
128
+ f"LIMIT {self._NUM_SAMPLE_ROWS}")
129
+ cursor.execute(sql)
97
130
  table = cursor.fetch_arrow_table()
98
- return table.to_pandas(types_mapper=pd.ArrowDtype)
99
131
 
100
- def _get_num_rows(self) -> Optional[int]:
132
+ if len(table) == 0:
133
+ raise RuntimeError(f"Table '{self.source_name}' is empty")
134
+
135
+ return self._sanitize(
136
+ df=table.to_pandas(types_mapper=pd.ArrowDtype),
137
+ dtype_dict={
138
+ column.name: column.dtype
139
+ for column in self._source_column_dict.values()
140
+ },
141
+ stype_dict=None,
142
+ )
143
+
144
+ def _get_num_rows(self) -> int | None:
101
145
  return None
146
+
147
+ def _get_expr_sample_df(
148
+ self,
149
+ columns: Sequence[ColumnSpec],
150
+ ) -> pd.DataFrame:
151
+ with self._connection.cursor() as cursor:
152
+ projections = [
153
+ f"{column.expr} AS {quote_ident(column.name)}"
154
+ for column in columns
155
+ ]
156
+ sql = (f"SELECT {', '.join(projections)} "
157
+ f"FROM {self._quoted_source_name} "
158
+ f"ORDER BY rowid "
159
+ f"LIMIT {self._NUM_SAMPLE_ROWS}")
160
+ cursor.execute(sql)
161
+ table = cursor.fetch_arrow_table()
162
+
163
+ if len(table) == 0:
164
+ raise RuntimeError(f"Table '{self.source_name}' is empty")
165
+
166
+ return self._sanitize(
167
+ df=table.to_pandas(types_mapper=pd.ArrowDtype),
168
+ dtype_dict={column.name: column.dtype
169
+ for column in columns},
170
+ stype_dict=None,
171
+ )
172
+
173
+ @staticmethod
174
+ def _to_dtype(dtype: str | None) -> Dtype | None:
175
+ if dtype is None:
176
+ return None
177
+ dtype = dtype.strip().upper()
178
+ if re.search('INT', dtype):
179
+ return Dtype.int
180
+ if re.search('TEXT|CHAR|CLOB', dtype):
181
+ return Dtype.string
182
+ if re.search('REAL|FLOA|DOUB', dtype):
183
+ return Dtype.float
184
+ return None # NUMERIC affinity.