kumoai 2.10.0.dev202509231831__cp313-cp313-macosx_11_0_arm64.whl → 2.14.0.dev202512161731__cp313-cp313-macosx_11_0_arm64.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.

Potentially problematic release.


This version of kumoai might be problematic. Click here for more details.

Files changed (53) hide show
  1. kumoai/__init__.py +22 -11
  2. kumoai/_version.py +1 -1
  3. kumoai/client/client.py +17 -16
  4. kumoai/client/endpoints.py +1 -0
  5. kumoai/client/pquery.py +6 -2
  6. kumoai/client/rfm.py +37 -8
  7. kumoai/connector/utils.py +23 -2
  8. kumoai/experimental/rfm/__init__.py +164 -46
  9. kumoai/experimental/rfm/backend/__init__.py +0 -0
  10. kumoai/experimental/rfm/backend/local/__init__.py +42 -0
  11. kumoai/experimental/rfm/{local_graph_store.py → backend/local/graph_store.py} +49 -86
  12. kumoai/experimental/rfm/backend/local/sampler.py +315 -0
  13. kumoai/experimental/rfm/backend/local/table.py +119 -0
  14. kumoai/experimental/rfm/backend/snow/__init__.py +37 -0
  15. kumoai/experimental/rfm/backend/snow/sampler.py +274 -0
  16. kumoai/experimental/rfm/backend/snow/table.py +135 -0
  17. kumoai/experimental/rfm/backend/sqlite/__init__.py +32 -0
  18. kumoai/experimental/rfm/backend/sqlite/sampler.py +353 -0
  19. kumoai/experimental/rfm/backend/sqlite/table.py +126 -0
  20. kumoai/experimental/rfm/base/__init__.py +25 -0
  21. kumoai/experimental/rfm/base/column.py +66 -0
  22. kumoai/experimental/rfm/base/sampler.py +773 -0
  23. kumoai/experimental/rfm/base/source.py +19 -0
  24. kumoai/experimental/rfm/base/sql_sampler.py +60 -0
  25. kumoai/experimental/rfm/{local_table.py → base/table.py} +245 -156
  26. kumoai/experimental/rfm/{local_graph.py → graph.py} +425 -137
  27. kumoai/experimental/rfm/infer/__init__.py +6 -0
  28. kumoai/experimental/rfm/infer/dtype.py +79 -0
  29. kumoai/experimental/rfm/infer/pkey.py +126 -0
  30. kumoai/experimental/rfm/infer/time_col.py +62 -0
  31. kumoai/experimental/rfm/infer/timestamp.py +7 -4
  32. kumoai/experimental/rfm/pquery/__init__.py +4 -4
  33. kumoai/experimental/rfm/pquery/{backend.py → executor.py} +24 -58
  34. kumoai/experimental/rfm/pquery/{pandas_backend.py → pandas_executor.py} +278 -224
  35. kumoai/experimental/rfm/rfm.py +669 -246
  36. kumoai/experimental/rfm/sagemaker.py +138 -0
  37. kumoai/jobs.py +1 -0
  38. kumoai/pquery/predictive_query.py +10 -6
  39. kumoai/spcs.py +1 -3
  40. kumoai/testing/decorators.py +1 -1
  41. kumoai/testing/snow.py +50 -0
  42. kumoai/trainer/trainer.py +12 -10
  43. kumoai/utils/__init__.py +3 -2
  44. kumoai/utils/progress_logger.py +239 -4
  45. kumoai/utils/sql.py +3 -0
  46. {kumoai-2.10.0.dev202509231831.dist-info → kumoai-2.14.0.dev202512161731.dist-info}/METADATA +15 -5
  47. {kumoai-2.10.0.dev202509231831.dist-info → kumoai-2.14.0.dev202512161731.dist-info}/RECORD +50 -32
  48. kumoai/experimental/rfm/local_graph_sampler.py +0 -176
  49. kumoai/experimental/rfm/local_pquery_driver.py +0 -404
  50. kumoai/experimental/rfm/utils.py +0 -344
  51. {kumoai-2.10.0.dev202509231831.dist-info → kumoai-2.14.0.dev202512161731.dist-info}/WHEEL +0 -0
  52. {kumoai-2.10.0.dev202509231831.dist-info → kumoai-2.14.0.dev202512161731.dist-info}/licenses/LICENSE +0 -0
  53. {kumoai-2.10.0.dev202509231831.dist-info → kumoai-2.14.0.dev202512161731.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,353 @@
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
+ from kumoapi.typing import Stype
10
+
11
+ from kumoai.experimental.rfm.backend.sqlite import SQLiteTable
12
+ from kumoai.experimental.rfm.base import SQLSampler
13
+ from kumoai.experimental.rfm.pquery import PQueryPandasExecutor
14
+ from kumoai.utils import ProgressLogger, quote_ident
15
+
16
+ if TYPE_CHECKING:
17
+ from kumoai.experimental.rfm import Graph
18
+
19
+
20
+ class SQLiteSampler(SQLSampler):
21
+ def __init__(
22
+ self,
23
+ graph: 'Graph',
24
+ verbose: bool | ProgressLogger = True,
25
+ optimize: bool = False,
26
+ ) -> None:
27
+ super().__init__(graph=graph, verbose=verbose)
28
+
29
+ for table in graph.tables.values():
30
+ assert isinstance(table, SQLiteTable)
31
+ self._connection = table._connection
32
+
33
+ if optimize:
34
+ with self._connection.cursor() as cursor:
35
+ cursor.execute("PRAGMA temp_store = MEMORY")
36
+ cursor.execute("PRAGMA cache_size = -2000000") # 2 GB
37
+
38
+ # Collect database indices to speed-up sampling:
39
+ index_dict: dict[str, set[tuple[str, ...]]] = defaultdict(set)
40
+ for table_name, primary_key in self.primary_key_dict.items():
41
+ source_table = self.source_table_dict[table_name]
42
+ if not source_table[primary_key].is_unique_key:
43
+ index_dict[table_name].add((primary_key, ))
44
+ for src_table_name, foreign_key, _ in graph.edges:
45
+ source_table = self.source_table_dict[src_table_name]
46
+ if source_table[foreign_key].is_unique_key:
47
+ pass
48
+ elif time_column := self.time_column_dict.get(src_table_name):
49
+ index_dict[src_table_name].add((foreign_key, time_column))
50
+ else:
51
+ index_dict[src_table_name].add((foreign_key, ))
52
+
53
+ # Only maintain missing indices:
54
+ with self._connection.cursor() as cursor:
55
+ for table_name in list(index_dict.keys()):
56
+ indices = index_dict[table_name]
57
+ sql = f"PRAGMA index_list({quote_ident(table_name)})"
58
+ cursor.execute(sql)
59
+ for _, index_name, *_ in cursor.fetchall():
60
+ sql = f"PRAGMA index_info({quote_ident(index_name)})"
61
+ cursor.execute(sql)
62
+ index = tuple(info[2] for info in sorted(
63
+ cursor.fetchall(), key=lambda x: x[0]))
64
+ indices.discard(index)
65
+ if len(indices) == 0:
66
+ del index_dict[table_name]
67
+
68
+ num = sum(len(indices) for indices in index_dict.values())
69
+ index_repr = '1 index' if num == 1 else f'{num} indices'
70
+ num = len(index_dict)
71
+ table_repr = '1 table' if num == 1 else f'{num} tables'
72
+
73
+ if optimize and len(index_dict) > 0:
74
+ if not isinstance(verbose, ProgressLogger):
75
+ verbose = ProgressLogger.default(
76
+ msg="Optimizing SQLite database",
77
+ verbose=verbose,
78
+ )
79
+
80
+ with verbose as logger, self._connection.cursor() as cursor:
81
+ for table_name, indices in index_dict.items():
82
+ for index in indices:
83
+ name = f"kumo_index_{table_name}_{'_'.join(index)}"
84
+ columns = ', '.join(quote_ident(v) for v in index)
85
+ columns += ' DESC' if len(index) > 1 else ''
86
+ sql = (f"CREATE INDEX IF NOT EXISTS {name}\n"
87
+ f"ON {quote_ident(table_name)}({columns})")
88
+ cursor.execute(sql)
89
+ self._connection.commit()
90
+ logger.log(f"Created {index_repr} in {table_repr}")
91
+
92
+ elif len(index_dict) > 0:
93
+ warnings.warn(f"Missing {index_repr} in {table_repr} for optimal "
94
+ f"database querying. For improving runtime, we "
95
+ f"strongly suggest to create these indices by "
96
+ f"instantiating KumoRFM via "
97
+ f"`KumoRFM(graph, optimize=True)`.")
98
+
99
+ def _get_min_max_time_dict(
100
+ self,
101
+ table_names: list[str],
102
+ ) -> dict[str, tuple[pd.Timestamp, pd.Timestamp]]:
103
+ selects: list[str] = []
104
+ for table_name in table_names:
105
+ time_column = self.time_column_dict[table_name]
106
+ select = (f"SELECT\n"
107
+ f" ? as table_name,\n"
108
+ f" MIN({quote_ident(time_column)}) as min_date,\n"
109
+ f" MAX({quote_ident(time_column)}) as max_date\n"
110
+ f"FROM {quote_ident(table_name)}")
111
+ selects.append(select)
112
+ sql = "\nUNION ALL\n".join(selects)
113
+
114
+ out_dict: dict[str, tuple[pd.Timestamp, pd.Timestamp]] = {}
115
+ with self._connection.cursor() as cursor:
116
+ cursor.execute(sql, table_names)
117
+ for table_name, _min, _max in cursor.fetchall():
118
+ out_dict[table_name] = (
119
+ pd.Timestamp.max if _min is None else pd.Timestamp(_min),
120
+ pd.Timestamp.min if _max is None else pd.Timestamp(_max),
121
+ )
122
+ return out_dict
123
+
124
+ def _sample_entity_table(
125
+ self,
126
+ table_name: str,
127
+ columns: set[str],
128
+ num_rows: int,
129
+ random_seed: int | None = None,
130
+ ) -> pd.DataFrame:
131
+ # NOTE SQLite does not natively support passing a `random_seed`.
132
+
133
+ filters: list[str] = []
134
+ primary_key = self.primary_key_dict[table_name]
135
+ if self.source_table_dict[table_name][primary_key].is_nullable:
136
+ filters.append(f" {quote_ident(primary_key)} IS NOT NULL")
137
+ time_column = self.time_column_dict.get(table_name)
138
+ if (time_column is not None and
139
+ self.source_table_dict[table_name][time_column].is_nullable):
140
+ filters.append(f" {quote_ident(time_column)} IS NOT NULL")
141
+
142
+ # TODO Make this query more efficient - it does full table scan.
143
+ sql = (f"SELECT {', '.join(quote_ident(col) for col in columns)}\n"
144
+ f"FROM {quote_ident(table_name)}")
145
+ if len(filters) > 0:
146
+ sql += f"\nWHERE{' AND'.join(filters)}"
147
+ sql += f"\nORDER BY RANDOM() LIMIT {num_rows}"
148
+
149
+ with self._connection.cursor() as cursor:
150
+ # NOTE This may return duplicate primary keys. This is okay.
151
+ cursor.execute(sql)
152
+ table = cursor.fetch_arrow_table()
153
+
154
+ return self._sanitize(table_name, table)
155
+
156
+ def _sample_target(
157
+ self,
158
+ query: ValidatedPredictiveQuery,
159
+ entity_df: pd.DataFrame,
160
+ train_index: np.ndarray,
161
+ train_time: pd.Series,
162
+ num_train_examples: int,
163
+ test_index: np.ndarray,
164
+ test_time: pd.Series,
165
+ num_test_examples: int,
166
+ columns_dict: dict[str, set[str]],
167
+ time_offset_dict: dict[
168
+ tuple[str, str, str],
169
+ tuple[pd.DateOffset | None, pd.DateOffset],
170
+ ],
171
+ ) -> tuple[pd.Series, np.ndarray, pd.Series, np.ndarray]:
172
+ train_y, train_mask = self._sample_target_set(
173
+ query=query,
174
+ entity_df=entity_df,
175
+ index=train_index,
176
+ anchor_time=train_time,
177
+ num_examples=num_train_examples,
178
+ columns_dict=columns_dict,
179
+ time_offset_dict=time_offset_dict,
180
+ )
181
+
182
+ test_y, test_mask = self._sample_target_set(
183
+ query=query,
184
+ entity_df=entity_df,
185
+ index=test_index,
186
+ anchor_time=test_time,
187
+ num_examples=num_test_examples,
188
+ columns_dict=columns_dict,
189
+ time_offset_dict=time_offset_dict,
190
+ )
191
+
192
+ return train_y, train_mask, test_y, test_mask
193
+
194
+ def _by_pkey(
195
+ self,
196
+ table_name: str,
197
+ pkey: pd.Series,
198
+ columns: set[str],
199
+ ) -> tuple[pd.DataFrame, np.ndarray]:
200
+ pkey_name = self.primary_key_dict[table_name]
201
+
202
+ tmp = pa.table([pa.array(pkey)], names=['id'])
203
+ tmp_name = f'tmp_{table_name}_{pkey_name}_{id(tmp)}'
204
+
205
+ if self.source_table_dict[table_name][pkey_name].is_unique_key:
206
+ sql = (f"SELECT tmp.rowid - 1 as __batch__, "
207
+ f"{', '.join('ent.' + quote_ident(c) for c in columns)}\n"
208
+ f"FROM {quote_ident(tmp_name)} tmp\n"
209
+ f"JOIN {quote_ident(table_name)} ent\n"
210
+ f" ON ent.{quote_ident(pkey_name)} = tmp.id")
211
+ else:
212
+ sql = (f"SELECT tmp.rowid - 1 as __batch__, "
213
+ f"{', '.join('ent.' + quote_ident(c) for c in columns)}\n"
214
+ f"FROM {quote_ident(tmp_name)} tmp\n"
215
+ f"JOIN {quote_ident(table_name)} ent\n"
216
+ f" ON ent.rowid = (\n"
217
+ f" SELECT rowid FROM {quote_ident(table_name)}\n"
218
+ f" WHERE {quote_ident(pkey_name)} == tmp.id\n"
219
+ f" LIMIT 1\n"
220
+ f")")
221
+
222
+ with self._connection.cursor() as cursor:
223
+ cursor.adbc_ingest(tmp_name, tmp, mode='replace')
224
+ cursor.execute(sql)
225
+ table = cursor.fetch_arrow_table()
226
+
227
+ batch = table['__batch__'].to_numpy()
228
+ table = table.remove_column(table.schema.get_field_index('__batch__'))
229
+
230
+ return table.to_pandas(), batch # TODO Use `self._sanitize`.
231
+
232
+ # Helper Methods ##########################################################
233
+
234
+ def _by_time(
235
+ self,
236
+ table_name: str,
237
+ fkey: str,
238
+ pkey: pd.Series,
239
+ anchor_time: pd.Series,
240
+ min_offset: pd.DateOffset | None,
241
+ max_offset: pd.DateOffset,
242
+ columns: set[str],
243
+ ) -> tuple[pd.DataFrame, np.ndarray]:
244
+ # NOTE SQLite does not have a native datetime format. Currently, we
245
+ # assume timestamps are given as `TEXT` in `ISO-8601 UTC`:
246
+ tmp = pa.table([pa.array(pkey)], names=['id'])
247
+ end_time = anchor_time + max_offset
248
+ end_time = end_time.dt.strftime("%Y-%m-%d %H:%M:%S")
249
+ tmp = tmp.append_column('end', pa.array(end_time))
250
+ if min_offset is not None:
251
+ start_time = anchor_time + min_offset
252
+ start_time = start_time.dt.strftime("%Y-%m-%d %H:%M:%S")
253
+ tmp = tmp.append_column('start', pa.array(start_time))
254
+ tmp_name = f'tmp_{table_name}_{fkey}_{id(tmp)}'
255
+
256
+ time_column = self.time_column_dict[table_name]
257
+ sql = (f"SELECT tmp.rowid - 1 as __batch__, "
258
+ f"{', '.join('fact.' + quote_ident(col) for col in columns)}\n"
259
+ f"FROM {quote_ident(tmp_name)} tmp\n"
260
+ f"JOIN {quote_ident(table_name)} fact\n"
261
+ f" ON fact.{quote_ident(fkey)} = tmp.id\n"
262
+ f" AND fact.{quote_ident(time_column)} <= tmp.end")
263
+ if min_offset is not None:
264
+ sql += f"\n AND fact.{quote_ident(time_column)} > tmp.start"
265
+
266
+ with self._connection.cursor() as cursor:
267
+ cursor.adbc_ingest(tmp_name, tmp, mode='replace')
268
+ cursor.execute(sql)
269
+ table = cursor.fetch_arrow_table()
270
+
271
+ batch = table['__batch__'].to_numpy()
272
+ table = table.remove_column(table.schema.get_field_index('__batch__'))
273
+
274
+ return self._sanitize(table_name, table), batch
275
+
276
+ def _sample_target_set(
277
+ self,
278
+ query: ValidatedPredictiveQuery,
279
+ entity_df: pd.DataFrame,
280
+ index: np.ndarray,
281
+ anchor_time: pd.Series,
282
+ num_examples: int,
283
+ columns_dict: dict[str, set[str]],
284
+ time_offset_dict: dict[
285
+ tuple[str, str, str],
286
+ tuple[pd.DateOffset | None, pd.DateOffset],
287
+ ],
288
+ batch_size: int = 10_000,
289
+ ) -> tuple[pd.Series, np.ndarray]:
290
+
291
+ count = 0
292
+ ys: list[pd.Series] = []
293
+ mask = np.full(len(index), False, dtype=bool)
294
+ for start in range(0, len(index), batch_size):
295
+ df = entity_df.iloc[index[start:start + batch_size]]
296
+ time = anchor_time.iloc[start:start + batch_size]
297
+
298
+ feat_dict: dict[str, pd.DataFrame] = {query.entity_table: df}
299
+ time_dict: dict[str, pd.Series] = {}
300
+ time_column = self.time_column_dict.get(query.entity_table)
301
+ if time_column in columns_dict[query.entity_table]:
302
+ time_dict[query.entity_table] = df[time_column]
303
+ batch_dict: dict[str, np.ndarray] = {
304
+ query.entity_table: np.arange(len(df)),
305
+ }
306
+ for edge_type, (_min, _max) in time_offset_dict.items():
307
+ table_name, fkey, _ = edge_type
308
+ feat_dict[table_name], batch_dict[table_name] = self._by_time(
309
+ table_name=table_name,
310
+ fkey=fkey,
311
+ pkey=df[self.primary_key_dict[query.entity_table]],
312
+ anchor_time=time,
313
+ min_offset=_min,
314
+ max_offset=_max,
315
+ columns=columns_dict[table_name],
316
+ )
317
+ time_column = self.time_column_dict.get(table_name)
318
+ if time_column in columns_dict[table_name]:
319
+ time_dict[table_name] = feat_dict[table_name][time_column]
320
+
321
+ y, _mask = PQueryPandasExecutor().execute(
322
+ query=query,
323
+ feat_dict=feat_dict,
324
+ time_dict=time_dict,
325
+ batch_dict=batch_dict,
326
+ anchor_time=anchor_time,
327
+ num_forecasts=query.num_forecasts,
328
+ )
329
+ ys.append(y)
330
+ mask[start:start + batch_size] = _mask
331
+
332
+ count += len(y)
333
+ if count >= num_examples:
334
+ break
335
+
336
+ if len(ys) == 0:
337
+ y = pd.Series([], dtype=float)
338
+ elif len(ys) == 1:
339
+ y = ys[0]
340
+ else:
341
+ y = pd.concat(ys, axis=0, ignore_index=True)
342
+
343
+ return y, mask
344
+
345
+ def _sanitize(self, table_name: str, table: pa.table) -> pd.DataFrame:
346
+ df = table.to_pandas(types_mapper=pd.ArrowDtype)
347
+
348
+ stype_dict = self.table_stype_dict[table_name]
349
+ for column_name in df.columns:
350
+ if stype_dict.get(column_name) == Stype.timestamp:
351
+ df[column_name] = pd.to_datetime(df[column_name])
352
+
353
+ return df
@@ -0,0 +1,126 @@
1
+ import re
2
+ import warnings
3
+ from typing import List, Optional, Sequence, cast
4
+
5
+ import pandas as pd
6
+ from kumoapi.typing import Dtype
7
+
8
+ from kumoai.experimental.rfm.backend.sqlite import Connection
9
+ from kumoai.experimental.rfm.base import (
10
+ DataBackend,
11
+ SourceColumn,
12
+ SourceForeignKey,
13
+ Table,
14
+ )
15
+ from kumoai.experimental.rfm.infer import infer_dtype
16
+ from kumoai.utils import quote_ident
17
+
18
+
19
+ class SQLiteTable(Table):
20
+ r"""A table backed by a :class:`sqlite` database.
21
+
22
+ Args:
23
+ connection: The connection to a :class:`sqlite` database.
24
+ name: The name of this table.
25
+ columns: The selected columns of this table.
26
+ primary_key: The name of the primary key of this table, if it exists.
27
+ time_column: The name of the time column of this table, if it exists.
28
+ end_time_column: The name of the end time column of this table, if it
29
+ exists.
30
+ """
31
+ def __init__(
32
+ self,
33
+ connection: Connection,
34
+ name: str,
35
+ columns: Optional[Sequence[str]] = None,
36
+ primary_key: Optional[str] = None,
37
+ time_column: Optional[str] = None,
38
+ end_time_column: Optional[str] = None,
39
+ ) -> None:
40
+
41
+ self._connection = connection
42
+
43
+ super().__init__(
44
+ name=name,
45
+ columns=columns,
46
+ primary_key=primary_key,
47
+ time_column=time_column,
48
+ end_time_column=end_time_column,
49
+ )
50
+
51
+ @property
52
+ def backend(self) -> DataBackend:
53
+ return cast(DataBackend, DataBackend.SQLITE)
54
+
55
+ def _get_source_columns(self) -> List[SourceColumn]:
56
+ source_columns: List[SourceColumn] = []
57
+ with self._connection.cursor() as cursor:
58
+ sql = f"PRAGMA table_info({quote_ident(self.name)})"
59
+ cursor.execute(sql)
60
+ columns = cursor.fetchall()
61
+
62
+ if len(columns) == 0:
63
+ raise ValueError(f"Table '{self.name}' does not exist")
64
+
65
+ unique_keys: set[str] = set()
66
+ sql = f"PRAGMA index_list({quote_ident(self.name)})"
67
+ cursor.execute(sql)
68
+ for _, index_name, is_unique, *_ in cursor.fetchall():
69
+ if bool(is_unique):
70
+ sql = f"PRAGMA index_info({quote_ident(index_name)})"
71
+ cursor.execute(sql)
72
+ index = cursor.fetchall()
73
+ if len(index) == 1:
74
+ unique_keys.add(index[0][2])
75
+
76
+ for _, column, type, notnull, _, is_pkey in columns:
77
+ # Determine column affinity:
78
+ type = type.strip().upper()
79
+ if re.search('INT', type):
80
+ dtype = Dtype.int
81
+ elif re.search('TEXT|CHAR|CLOB', type):
82
+ dtype = Dtype.string
83
+ elif re.search('REAL|FLOA|DOUB', type):
84
+ dtype = Dtype.float
85
+ else: # NUMERIC affinity.
86
+ ser = self._sample_df[column]
87
+ try:
88
+ dtype = infer_dtype(ser)
89
+ except Exception:
90
+ warnings.warn(
91
+ f"Data type inference for column '{column}' in "
92
+ f"table '{self.name}' failed. Consider changing "
93
+ f"the data type of the column to use it within "
94
+ f"this table.")
95
+ continue
96
+
97
+ source_column = SourceColumn(
98
+ name=column,
99
+ dtype=dtype,
100
+ is_primary_key=bool(is_pkey),
101
+ is_unique_key=column in unique_keys,
102
+ is_nullable=not bool(is_pkey) and not bool(notnull),
103
+ )
104
+ source_columns.append(source_column)
105
+
106
+ return source_columns
107
+
108
+ def _get_source_foreign_keys(self) -> List[SourceForeignKey]:
109
+ source_fkeys: List[SourceForeignKey] = []
110
+ with self._connection.cursor() as cursor:
111
+ sql = f"PRAGMA foreign_key_list({quote_ident(self.name)})"
112
+ cursor.execute(sql)
113
+ for _, _, dst_table, fkey, pkey, *_ in cursor.fetchall():
114
+ source_fkeys.append(SourceForeignKey(fkey, dst_table, pkey))
115
+ return source_fkeys
116
+
117
+ def _get_sample_df(self) -> pd.DataFrame:
118
+ with self._connection.cursor() as cursor:
119
+ sql = (f"SELECT * FROM {quote_ident(self.name)} "
120
+ f"ORDER BY rowid LIMIT 1000")
121
+ cursor.execute(sql)
122
+ table = cursor.fetch_arrow_table()
123
+ return table.to_pandas(types_mapper=pd.ArrowDtype)
124
+
125
+ def _get_num_rows(self) -> Optional[int]:
126
+ return None
@@ -0,0 +1,25 @@
1
+ from kumoapi.common import StrEnum
2
+
3
+
4
+ class DataBackend(StrEnum):
5
+ LOCAL = 'local'
6
+ SQLITE = 'sqlite'
7
+ SNOWFLAKE = 'snowflake'
8
+
9
+
10
+ from .source import SourceColumn, SourceForeignKey # noqa: E402
11
+ from .column import Column # noqa: E402
12
+ from .table import Table # noqa: E402
13
+ from .sampler import SamplerOutput, Sampler # noqa: E402
14
+ from .sql_sampler import SQLSampler # noqa: E402
15
+
16
+ __all__ = [
17
+ 'DataBackend',
18
+ 'SourceColumn',
19
+ 'SourceForeignKey',
20
+ 'Column',
21
+ 'Table',
22
+ 'SamplerOutput',
23
+ 'Sampler',
24
+ 'SQLSampler',
25
+ ]
@@ -0,0 +1,66 @@
1
+ from dataclasses import dataclass
2
+ from typing import Any
3
+
4
+ from kumoapi.typing import Dtype, Stype
5
+
6
+
7
+ @dataclass(init=False, repr=False, eq=False)
8
+ class Column:
9
+ stype: Stype
10
+
11
+ def __init__(
12
+ self,
13
+ name: str,
14
+ dtype: Dtype,
15
+ stype: Stype,
16
+ is_primary_key: bool = False,
17
+ is_time_column: bool = False,
18
+ is_end_time_column: bool = False,
19
+ ) -> None:
20
+ self._name = name
21
+ self._dtype = Dtype(dtype)
22
+ self._is_primary_key = is_primary_key
23
+ self._is_time_column = is_time_column
24
+ self._is_end_time_column = is_end_time_column
25
+ self.stype = Stype(stype)
26
+
27
+ @property
28
+ def name(self) -> str:
29
+ return self._name
30
+
31
+ @property
32
+ def dtype(self) -> Dtype:
33
+ return self._dtype
34
+
35
+ def __setattr__(self, key: str, val: Any) -> None:
36
+ if key == 'stype':
37
+ if isinstance(val, str):
38
+ val = Stype(val)
39
+ assert isinstance(val, Stype)
40
+ if not val.supports_dtype(self.dtype):
41
+ raise ValueError(f"Column '{self.name}' received an "
42
+ f"incompatible semantic type (got "
43
+ f"dtype='{self.dtype}' and stype='{val}')")
44
+ if self._is_primary_key and val != Stype.ID:
45
+ raise ValueError(f"Primary key '{self.name}' must have 'ID' "
46
+ f"semantic type (got '{val}')")
47
+ if self._is_time_column and val != Stype.timestamp:
48
+ raise ValueError(f"Time column '{self.name}' must have "
49
+ f"'timestamp' semantic type (got '{val}')")
50
+ if self._is_end_time_column and val != Stype.timestamp:
51
+ raise ValueError(f"End time column '{self.name}' must have "
52
+ f"'timestamp' semantic type (got '{val}')")
53
+
54
+ super().__setattr__(key, val)
55
+
56
+ def __hash__(self) -> int:
57
+ return hash((self.name, self.stype, self.dtype))
58
+
59
+ def __eq__(self, other: Any) -> bool:
60
+ if not isinstance(other, Column):
61
+ return False
62
+ return hash(self) == hash(other)
63
+
64
+ def __repr__(self) -> str:
65
+ return (f'{self.__class__.__name__}(name={self.name}, '
66
+ f'stype={self.stype}, dtype={self.dtype})')