kumoai 2.13.0.dev202511271731__cp312-cp312-win_amd64.whl → 2.14.0.dev202512111731__cp312-cp312-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 (37) hide show
  1. kumoai/__init__.py +12 -0
  2. kumoai/_version.py +1 -1
  3. kumoai/connector/utils.py +23 -2
  4. kumoai/experimental/rfm/__init__.py +20 -45
  5. kumoai/experimental/rfm/backend/__init__.py +0 -0
  6. kumoai/experimental/rfm/backend/local/__init__.py +42 -0
  7. kumoai/experimental/rfm/{local_graph_store.py → backend/local/graph_store.py} +37 -90
  8. kumoai/experimental/rfm/backend/local/sampler.py +313 -0
  9. kumoai/experimental/rfm/backend/local/table.py +109 -0
  10. kumoai/experimental/rfm/backend/snow/__init__.py +35 -0
  11. kumoai/experimental/rfm/backend/snow/table.py +117 -0
  12. kumoai/experimental/rfm/backend/sqlite/__init__.py +30 -0
  13. kumoai/experimental/rfm/backend/sqlite/table.py +101 -0
  14. kumoai/experimental/rfm/base/__init__.py +13 -0
  15. kumoai/experimental/rfm/base/column.py +66 -0
  16. kumoai/experimental/rfm/base/sampler.py +763 -0
  17. kumoai/experimental/rfm/base/source.py +18 -0
  18. kumoai/experimental/rfm/{local_table.py → base/table.py} +139 -139
  19. kumoai/experimental/rfm/{local_graph.py → graph.py} +334 -79
  20. kumoai/experimental/rfm/infer/__init__.py +6 -0
  21. kumoai/experimental/rfm/infer/dtype.py +79 -0
  22. kumoai/experimental/rfm/infer/pkey.py +126 -0
  23. kumoai/experimental/rfm/infer/time_col.py +62 -0
  24. kumoai/experimental/rfm/pquery/pandas_executor.py +1 -1
  25. kumoai/experimental/rfm/rfm.py +204 -166
  26. kumoai/experimental/rfm/sagemaker.py +11 -3
  27. kumoai/kumolib.cp312-win_amd64.pyd +0 -0
  28. kumoai/pquery/predictive_query.py +10 -6
  29. kumoai/testing/decorators.py +1 -1
  30. {kumoai-2.13.0.dev202511271731.dist-info → kumoai-2.14.0.dev202512111731.dist-info}/METADATA +9 -8
  31. {kumoai-2.13.0.dev202511271731.dist-info → kumoai-2.14.0.dev202512111731.dist-info}/RECORD +34 -22
  32. kumoai/experimental/rfm/local_graph_sampler.py +0 -182
  33. kumoai/experimental/rfm/local_pquery_driver.py +0 -689
  34. kumoai/experimental/rfm/utils.py +0 -344
  35. {kumoai-2.13.0.dev202511271731.dist-info → kumoai-2.14.0.dev202512111731.dist-info}/WHEEL +0 -0
  36. {kumoai-2.13.0.dev202511271731.dist-info → kumoai-2.14.0.dev202512111731.dist-info}/licenses/LICENSE +0 -0
  37. {kumoai-2.13.0.dev202511271731.dist-info → kumoai-2.14.0.dev202512111731.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,313 @@
1
+ from typing import TYPE_CHECKING, Literal
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ from kumoapi.pquery import ValidatedPredictiveQuery
6
+
7
+ from kumoai.experimental.rfm.backend.local import LocalGraphStore
8
+ from kumoai.experimental.rfm.base import Sampler, SamplerOutput
9
+ from kumoai.experimental.rfm.pquery import PQueryPandasExecutor
10
+ from kumoai.utils import ProgressLogger
11
+
12
+ if TYPE_CHECKING:
13
+ from kumoai.experimental.rfm import Graph
14
+
15
+
16
+ class LocalSampler(Sampler):
17
+ def __init__(
18
+ self,
19
+ graph: 'Graph',
20
+ verbose: bool | ProgressLogger = True,
21
+ ) -> None:
22
+ super().__init__(graph=graph)
23
+
24
+ import kumoai.kumolib as kumolib
25
+
26
+ self._graph_store = LocalGraphStore(graph, verbose)
27
+ self._graph_sampler = kumolib.NeighborSampler(
28
+ list(self.table_stype_dict.keys()),
29
+ self.edge_types,
30
+ {
31
+ '__'.join(edge_type): colptr
32
+ for edge_type, colptr in self._graph_store.colptr_dict.items()
33
+ },
34
+ {
35
+ '__'.join(edge_type): row
36
+ for edge_type, row in self._graph_store.row_dict.items()
37
+ },
38
+ self._graph_store.time_dict,
39
+ )
40
+
41
+ def _get_min_max_time_dict(
42
+ self,
43
+ table_names: list[str],
44
+ ) -> dict[str, tuple[pd.Timestamp, pd.Timestamp]]:
45
+ return {
46
+ key: value
47
+ for key, value in self._graph_store.min_max_time_dict.items()
48
+ if key in table_names
49
+ }
50
+
51
+ def _sample_subgraph(
52
+ self,
53
+ entity_table_name: str,
54
+ entity_pkey: pd.Series,
55
+ anchor_time: pd.Series | Literal['entity'],
56
+ columns_dict: dict[str, set[str]],
57
+ num_neighbors: list[int],
58
+ ) -> SamplerOutput:
59
+
60
+ index = self._graph_store.get_node_id(entity_table_name, entity_pkey)
61
+
62
+ if isinstance(anchor_time, pd.Series):
63
+ time = anchor_time.astype(int).to_numpy() // 1000**3 # to seconds
64
+ else:
65
+ assert anchor_time == 'entity'
66
+ time = self._graph_store.time_dict[entity_table_name][index]
67
+
68
+ (
69
+ row_dict,
70
+ col_dict,
71
+ node_dict,
72
+ batch_dict,
73
+ num_sampled_nodes_dict,
74
+ num_sampled_edges_dict,
75
+ ) = self._graph_sampler.sample(
76
+ {
77
+ '__'.join(edge_type): num_neighbors
78
+ for edge_type in self.edge_types
79
+ },
80
+ {},
81
+ entity_table_name,
82
+ index,
83
+ time,
84
+ )
85
+
86
+ df_dict: dict[str, pd.DataFrame] = {}
87
+ inverse_dict: dict[str, np.ndarray] = {}
88
+ for table_name, node in node_dict.items():
89
+ df = self._graph_store.df_dict[table_name]
90
+ columns = columns_dict[table_name]
91
+ if self.end_time_column_dict.get(table_name, None) in columns:
92
+ df = df.iloc[node]
93
+ elif len(columns) == 0:
94
+ df = df.iloc[node]
95
+ else:
96
+ # Only store unique rows in `df` above a certain threshold:
97
+ unique_node, inverse = np.unique(node, return_inverse=True)
98
+ if len(node) > 1.05 * len(unique_node):
99
+ df = df.iloc[unique_node]
100
+ inverse_dict[table_name] = inverse
101
+ else:
102
+ df = df.iloc[node]
103
+ df = df.reset_index(drop=True)
104
+ df = df[list(columns)]
105
+ df_dict[table_name] = df
106
+
107
+ num_sampled_nodes_dict = {
108
+ table_name: num_sampled_nodes.tolist()
109
+ for table_name, num_sampled_nodes in
110
+ num_sampled_nodes_dict.items()
111
+ }
112
+
113
+ row_dict = {
114
+ edge_type: row_dict['__'.join(edge_type)]
115
+ for edge_type in self.edge_types
116
+ }
117
+ col_dict = {
118
+ edge_type: col_dict['__'.join(edge_type)]
119
+ for edge_type in self.edge_types
120
+ }
121
+ num_sampled_edges_dict = {
122
+ edge_type: num_sampled_edges_dict['__'.join(edge_type)].tolist()
123
+ for edge_type in self.edge_types
124
+ }
125
+
126
+ return SamplerOutput(
127
+ anchor_time=time * 1000**3, # to nanoseconds
128
+ df_dict=df_dict,
129
+ inverse_dict=inverse_dict,
130
+ batch_dict=batch_dict,
131
+ num_sampled_nodes_dict=num_sampled_nodes_dict,
132
+ row_dict=row_dict,
133
+ col_dict=col_dict,
134
+ num_sampled_edges_dict=num_sampled_edges_dict,
135
+ )
136
+
137
+ def _sample_entity_table(
138
+ self,
139
+ table_name: str,
140
+ columns: set[str],
141
+ num_rows: int,
142
+ random_seed: int | None = None,
143
+ ) -> pd.DataFrame:
144
+ pkey_map = self._graph_store.pkey_map_dict[table_name]
145
+ if len(pkey_map) > num_rows:
146
+ pkey_map = pkey_map.sample(
147
+ n=num_rows,
148
+ random_state=random_seed,
149
+ ignore_index=True,
150
+ )
151
+ df = self._graph_store.df_dict[table_name]
152
+ df = df.iloc[pkey_map['arange']][list(columns)]
153
+ return df
154
+
155
+ def _sample_target(
156
+ self,
157
+ query: ValidatedPredictiveQuery,
158
+ entity_df: pd.DataFrame,
159
+ train_index: np.ndarray,
160
+ train_time: pd.Series,
161
+ num_train_examples: int,
162
+ test_index: np.ndarray,
163
+ test_time: pd.Series,
164
+ num_test_examples: int,
165
+ columns_dict: dict[str, set[str]],
166
+ time_offset_dict: dict[
167
+ tuple[str, str, str],
168
+ tuple[pd.DateOffset | None, pd.DateOffset],
169
+ ],
170
+ ) -> tuple[pd.Series, np.ndarray, pd.Series, np.ndarray]:
171
+
172
+ train_y, train_mask = self._sample_target_set(
173
+ query=query,
174
+ pkey=entity_df[self.primary_key_dict[query.entity_table]],
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
+ pkey=entity_df[self.primary_key_dict[query.entity_table]],
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 _sample_target_set(
195
+ self,
196
+ query: ValidatedPredictiveQuery,
197
+ pkey: pd.Series,
198
+ index: np.ndarray,
199
+ anchor_time: pd.Series,
200
+ num_examples: int,
201
+ columns_dict: dict[str, set[str]],
202
+ time_offset_dict: dict[
203
+ tuple[str, str, str],
204
+ tuple[pd.DateOffset | None, pd.DateOffset],
205
+ ],
206
+ batch_size: int = 10_000,
207
+ ) -> tuple[pd.Series, np.ndarray]:
208
+
209
+ num_hops = 1 if len(time_offset_dict) > 0 else 0
210
+ num_neighbors_dict: dict[str, list[int]] = {}
211
+ unix_time_offset_dict: dict[str, list[list[int | None]]] = {}
212
+ for edge_type, (start, end) in time_offset_dict.items():
213
+ unix_time_offset_dict['__'.join(edge_type)] = [[
214
+ date_offset_to_seconds(start) if start is not None else None,
215
+ date_offset_to_seconds(end),
216
+ ]]
217
+ for edge_type in set(self.edge_types) - set(time_offset_dict.keys()):
218
+ num_neighbors_dict['__'.join(edge_type)] = [0] * num_hops
219
+
220
+ if anchor_time.dtype != 'datetime64[ns]':
221
+ anchor_time = anchor_time.astype('datetime64')
222
+
223
+ count = 0
224
+ ys: list[pd.Series] = []
225
+ mask = np.full(len(index), False, dtype=bool)
226
+ for start in range(0, len(index), batch_size):
227
+ subset = pkey.iloc[index[start:start + batch_size]]
228
+ time = anchor_time.iloc[start:start + batch_size]
229
+
230
+ _, _, node_dict, batch_dict, _, _ = self._graph_sampler.sample(
231
+ num_neighbors_dict,
232
+ unix_time_offset_dict,
233
+ query.entity_table,
234
+ self._graph_store.get_node_id(query.entity_table, subset),
235
+ time.astype(int).to_numpy() // 1000**3, # to seconds
236
+ )
237
+
238
+ feat_dict: dict[str, pd.DataFrame] = {}
239
+ time_dict: dict[str, pd.Series] = {}
240
+ for table_name, columns in columns_dict.items():
241
+ df = self._graph_store.df_dict[table_name]
242
+ df = df.iloc[node_dict[table_name]].reset_index(drop=True)
243
+ df = df[list(columns)]
244
+ feat_dict[table_name] = df
245
+
246
+ time_column = self.time_column_dict.get(table_name)
247
+ if time_column in columns:
248
+ time_dict[table_name] = df[time_column]
249
+
250
+ y, _mask = PQueryPandasExecutor().execute(
251
+ query=query,
252
+ feat_dict=feat_dict,
253
+ time_dict=time_dict,
254
+ batch_dict=batch_dict,
255
+ anchor_time=time,
256
+ num_forecasts=query.num_forecasts,
257
+ )
258
+ ys.append(y)
259
+ mask[start:start + batch_size] = _mask
260
+
261
+ count += len(y)
262
+ if count >= num_examples:
263
+ break
264
+
265
+ if len(ys) == 0:
266
+ y = pd.Series([], dtype=float)
267
+ elif len(ys) == 1:
268
+ y = ys[0]
269
+ else:
270
+ y = pd.concat(ys, axis=0, ignore_index=True)
271
+
272
+ return y, mask
273
+
274
+
275
+ # Helper Methods ##############################################################
276
+
277
+
278
+ def date_offset_to_seconds(offset: pd.DateOffset) -> int:
279
+ r"""Convert a :class:`pandas.DateOffset` into a number of seconds.
280
+
281
+ .. note::
282
+ We are conservative and take months and years as their maximum value.
283
+ Additional values are then dropped in label computation where we know
284
+ the actual dates.
285
+ """
286
+ MAX_DAYS_IN_MONTH = 31
287
+ MAX_DAYS_IN_YEAR = 366
288
+
289
+ SECONDS_IN_MINUTE = 60
290
+ SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTE
291
+ SECONDS_IN_DAY = 24 * SECONDS_IN_HOUR
292
+
293
+ total_sec = 0
294
+ multiplier = getattr(offset, 'n', 1) # The multiplier (if present).
295
+
296
+ for attr, value in offset.__dict__.items():
297
+ if value is None or value == 0:
298
+ continue
299
+ scaled_value = value * multiplier
300
+ if attr == 'years':
301
+ total_sec += scaled_value * MAX_DAYS_IN_YEAR * SECONDS_IN_DAY
302
+ elif attr == 'months':
303
+ total_sec += scaled_value * MAX_DAYS_IN_MONTH * SECONDS_IN_DAY
304
+ elif attr == 'days':
305
+ total_sec += scaled_value * SECONDS_IN_DAY
306
+ elif attr == 'hours':
307
+ total_sec += scaled_value * SECONDS_IN_HOUR
308
+ elif attr == 'minutes':
309
+ total_sec += scaled_value * SECONDS_IN_MINUTE
310
+ elif attr == 'seconds':
311
+ total_sec += scaled_value
312
+
313
+ return total_sec
@@ -0,0 +1,109 @@
1
+ import warnings
2
+ from typing import List, Optional
3
+
4
+ import pandas as pd
5
+
6
+ from kumoai.experimental.rfm.base import SourceColumn, SourceForeignKey, Table
7
+ from kumoai.experimental.rfm.infer import infer_dtype
8
+
9
+
10
+ class LocalTable(Table):
11
+ r"""A table backed by a :class:`pandas.DataFrame`.
12
+
13
+ A :class:`LocalTable` fully specifies the relevant metadata, *i.e.*
14
+ selected columns, column semantic types, primary keys and time columns.
15
+ :class:`LocalTable` is used to create a :class:`Graph`.
16
+
17
+ .. code-block:: python
18
+
19
+ import pandas as pd
20
+ import kumoai.experimental.rfm as rfm
21
+
22
+ # Load data from a CSV file:
23
+ df = pd.read_csv("data.csv")
24
+
25
+ # Create a table from a `pandas.DataFrame` and infer its metadata ...
26
+ table = rfm.LocalTable(df, name="my_table").infer_metadata()
27
+
28
+ # ... or create a table explicitly:
29
+ table = rfm.LocalTable(
30
+ df=df,
31
+ name="my_table",
32
+ primary_key="id",
33
+ time_column="time",
34
+ end_time_column=None,
35
+ )
36
+
37
+ # Verify metadata:
38
+ table.print_metadata()
39
+
40
+ # Change the semantic type of a column:
41
+ table[column].stype = "text"
42
+
43
+ Args:
44
+ df: The data frame to create this table from.
45
+ name: The name of this table.
46
+ primary_key: The name of the primary key of this table, if it exists.
47
+ time_column: The name of the time column of this table, if it exists.
48
+ end_time_column: The name of the end time column of this table, if it
49
+ exists.
50
+ """
51
+ def __init__(
52
+ self,
53
+ df: pd.DataFrame,
54
+ name: str,
55
+ primary_key: Optional[str] = None,
56
+ time_column: Optional[str] = None,
57
+ end_time_column: Optional[str] = None,
58
+ ) -> None:
59
+
60
+ if df.empty:
61
+ raise ValueError("Data frame is empty")
62
+ if isinstance(df.columns, pd.MultiIndex):
63
+ raise ValueError("Data frame must not have a multi-index")
64
+ if not df.columns.is_unique:
65
+ raise ValueError("Data frame must have unique column names")
66
+ if any(col == '' for col in df.columns):
67
+ raise ValueError("Data frame must have non-empty column names")
68
+
69
+ self._data = df.copy(deep=False)
70
+
71
+ super().__init__(
72
+ name=name,
73
+ columns=list(df.columns),
74
+ primary_key=primary_key,
75
+ time_column=time_column,
76
+ end_time_column=end_time_column,
77
+ )
78
+
79
+ def _get_source_columns(self) -> List[SourceColumn]:
80
+ source_columns: List[SourceColumn] = []
81
+ for column in self._data.columns:
82
+ ser = self._data[column]
83
+ try:
84
+ dtype = infer_dtype(ser)
85
+ except Exception:
86
+ warnings.warn(f"Data type inference for column '{column}' in "
87
+ f"table '{self.name}' failed. Consider changing "
88
+ f"the data type of the column to use it within "
89
+ f"this table.")
90
+ continue
91
+
92
+ source_column = SourceColumn(
93
+ name=column,
94
+ dtype=dtype,
95
+ is_primary_key=False,
96
+ is_unique_key=False,
97
+ )
98
+ source_columns.append(source_column)
99
+
100
+ return source_columns
101
+
102
+ def _get_source_foreign_keys(self) -> List[SourceForeignKey]:
103
+ return []
104
+
105
+ def _get_sample_df(self) -> pd.DataFrame:
106
+ return self._data
107
+
108
+ def _get_num_rows(self) -> Optional[int]:
109
+ return len(self._data)
@@ -0,0 +1,35 @@
1
+ from typing import Any, TypeAlias
2
+
3
+ try:
4
+ import snowflake.connector
5
+ except ImportError:
6
+ raise ImportError("No module named 'snowflake'. Please install Kumo SDK "
7
+ "with the 'snowflake' extension via "
8
+ "`pip install kumoai[snowflake]`.")
9
+
10
+ Connection: TypeAlias = snowflake.connector.SnowflakeConnection
11
+
12
+
13
+ def connect(**kwargs: Any) -> Connection:
14
+ r"""Opens a connection to a :class:`snowflake` database.
15
+
16
+ If available, will return a connection to the active session.
17
+
18
+ kwargs: Connection arguments, following the :class:`snowflake` protocol.
19
+ """
20
+ try:
21
+ from snowflake.snowpark.context import get_active_session
22
+ return get_active_session().connection
23
+ except Exception:
24
+ pass
25
+
26
+ return snowflake.connector.connect(**kwargs)
27
+
28
+
29
+ from .table import SnowTable # noqa: E402
30
+
31
+ __all__ = [
32
+ 'connect',
33
+ 'Connection',
34
+ 'SnowTable',
35
+ ]
@@ -0,0 +1,117 @@
1
+ import re
2
+ from typing import List, Optional, Sequence
3
+
4
+ import pandas as pd
5
+ from kumoapi.typing import Dtype
6
+
7
+ from kumoai.experimental.rfm.backend.snow import Connection
8
+ from kumoai.experimental.rfm.base import SourceColumn, SourceForeignKey, Table
9
+
10
+
11
+ class SnowTable(Table):
12
+ r"""A table backed by a :class:`sqlite` database.
13
+
14
+ Args:
15
+ connection: The connection to a :class:`snowflake` database.
16
+ name: The name of this table.
17
+ database: The database.
18
+ schema: The schema.
19
+ columns: The selected columns of this table.
20
+ primary_key: The name of the primary key of this table, if it exists.
21
+ time_column: The name of the time column of this table, if it exists.
22
+ end_time_column: The name of the end time column of this table, if it
23
+ exists.
24
+ """
25
+ def __init__(
26
+ self,
27
+ connection: Connection,
28
+ name: str,
29
+ database: str | None = None,
30
+ schema: str | None = None,
31
+ columns: Optional[Sequence[str]] = None,
32
+ primary_key: Optional[str] = None,
33
+ time_column: Optional[str] = None,
34
+ end_time_column: Optional[str] = None,
35
+ ) -> None:
36
+
37
+ if database is not None and schema is None:
38
+ raise ValueError(f"Missing 'schema' for table '{name}' in "
39
+ f"database '{database}'")
40
+
41
+ self._connection = connection
42
+ self._database = database
43
+ self._schema = schema
44
+
45
+ super().__init__(
46
+ name=name,
47
+ columns=columns,
48
+ primary_key=primary_key,
49
+ time_column=time_column,
50
+ end_time_column=end_time_column,
51
+ )
52
+
53
+ @property
54
+ def fqn_name(self) -> str:
55
+ names: List[str] = []
56
+ if self._database is not None:
57
+ assert self._schema is not None
58
+ names.extend([self._database, self._schema])
59
+ elif self._schema is not None:
60
+ names.append(self._schema)
61
+ names.append(self._name)
62
+ return '.'.join(names)
63
+
64
+ def _get_source_columns(self) -> List[SourceColumn]:
65
+ source_columns: List[SourceColumn] = []
66
+ with self._connection.cursor() as cursor:
67
+ try:
68
+ cursor.execute(f"DESCRIBE TABLE {self.fqn_name}")
69
+ except Exception as e:
70
+ raise ValueError(
71
+ f"Table '{self.fqn_name}' does not exist") from e
72
+
73
+ for row in cursor.fetchall():
74
+ column, type, _, _, _, is_pkey, is_unique = row[:7]
75
+
76
+ type = type.strip().upper()
77
+ if type.startswith('NUMBER'):
78
+ dtype = Dtype.int
79
+ elif type.startswith('VARCHAR'):
80
+ dtype = Dtype.string
81
+ elif type == 'FLOAT':
82
+ dtype = Dtype.float
83
+ elif type == 'BOOLEAN':
84
+ dtype = Dtype.bool
85
+ elif re.search('DATE|TIMESTAMP', type):
86
+ dtype = Dtype.date
87
+ else:
88
+ continue
89
+
90
+ source_column = SourceColumn(
91
+ name=column,
92
+ dtype=dtype,
93
+ is_primary_key=is_pkey.strip().upper() == 'Y',
94
+ is_unique_key=is_unique.strip().upper() == 'Y',
95
+ )
96
+ source_columns.append(source_column)
97
+
98
+ return source_columns
99
+
100
+ def _get_source_foreign_keys(self) -> List[SourceForeignKey]:
101
+ source_fkeys: List[SourceForeignKey] = []
102
+ with self._connection.cursor() as cursor:
103
+ cursor.execute(f"SHOW IMPORTED KEYS IN TABLE {self.fqn_name}")
104
+ for row in cursor.fetchall():
105
+ _, _, _, dst_table, pkey, _, _, _, fkey = row[:9]
106
+ source_fkeys.append(SourceForeignKey(fkey, dst_table, pkey))
107
+ return source_fkeys
108
+
109
+ def _get_sample_df(self) -> pd.DataFrame:
110
+ with self._connection.cursor() as cursor:
111
+ columns = ', '.join(self._source_column_dict.keys())
112
+ cursor.execute(f"SELECT {columns} FROM {self.fqn_name} LIMIT 1000")
113
+ table = cursor.fetch_arrow_all()
114
+ return table.to_pandas(types_mapper=pd.ArrowDtype)
115
+
116
+ def _get_num_rows(self) -> Optional[int]:
117
+ return None
@@ -0,0 +1,30 @@
1
+ from pathlib import Path
2
+ from typing import Any, TypeAlias, Union
3
+
4
+ try:
5
+ import adbc_driver_sqlite.dbapi as adbc
6
+ except ImportError:
7
+ raise ImportError("No module named 'adbc_driver_sqlite'. Please install "
8
+ "Kumo SDK with the 'sqlite' extension via "
9
+ "`pip install kumoai[sqlite]`.")
10
+
11
+ Connection: TypeAlias = adbc.AdbcSqliteConnection
12
+
13
+
14
+ def connect(uri: Union[str, Path, None] = None, **kwargs: Any) -> Connection:
15
+ r"""Opens a connection to a :class:`sqlite` database.
16
+
17
+ uri: The path to the database file to be opened.
18
+ kwargs: Additional connection arguments, following the
19
+ :class:`adbc_driver_sqlite` protocol.
20
+ """
21
+ return adbc.connect(uri, **kwargs)
22
+
23
+
24
+ from .table import SQLiteTable # noqa: E402
25
+
26
+ __all__ = [
27
+ 'connect',
28
+ 'Connection',
29
+ 'SQLiteTable',
30
+ ]