pixeltable 0.1.0__py3-none-any.whl → 0.2.4__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.

Potentially problematic release.


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

Files changed (147) hide show
  1. pixeltable/__init__.py +34 -6
  2. pixeltable/catalog/__init__.py +13 -0
  3. pixeltable/catalog/catalog.py +159 -0
  4. pixeltable/catalog/column.py +200 -0
  5. pixeltable/catalog/dir.py +32 -0
  6. pixeltable/catalog/globals.py +33 -0
  7. pixeltable/catalog/insertable_table.py +191 -0
  8. pixeltable/catalog/named_function.py +36 -0
  9. pixeltable/catalog/path.py +58 -0
  10. pixeltable/catalog/path_dict.py +139 -0
  11. pixeltable/catalog/schema_object.py +39 -0
  12. pixeltable/catalog/table.py +581 -0
  13. pixeltable/catalog/table_version.py +749 -0
  14. pixeltable/catalog/table_version_path.py +133 -0
  15. pixeltable/catalog/view.py +203 -0
  16. pixeltable/client.py +590 -30
  17. pixeltable/dataframe.py +540 -349
  18. pixeltable/env.py +359 -45
  19. pixeltable/exceptions.py +12 -21
  20. pixeltable/exec/__init__.py +9 -0
  21. pixeltable/exec/aggregation_node.py +78 -0
  22. pixeltable/exec/cache_prefetch_node.py +116 -0
  23. pixeltable/exec/component_iteration_node.py +79 -0
  24. pixeltable/exec/data_row_batch.py +95 -0
  25. pixeltable/exec/exec_context.py +22 -0
  26. pixeltable/exec/exec_node.py +61 -0
  27. pixeltable/exec/expr_eval_node.py +217 -0
  28. pixeltable/exec/in_memory_data_node.py +69 -0
  29. pixeltable/exec/media_validation_node.py +43 -0
  30. pixeltable/exec/sql_scan_node.py +225 -0
  31. pixeltable/exprs/__init__.py +24 -0
  32. pixeltable/exprs/arithmetic_expr.py +102 -0
  33. pixeltable/exprs/array_slice.py +71 -0
  34. pixeltable/exprs/column_property_ref.py +77 -0
  35. pixeltable/exprs/column_ref.py +105 -0
  36. pixeltable/exprs/comparison.py +77 -0
  37. pixeltable/exprs/compound_predicate.py +98 -0
  38. pixeltable/exprs/data_row.py +195 -0
  39. pixeltable/exprs/expr.py +586 -0
  40. pixeltable/exprs/expr_set.py +39 -0
  41. pixeltable/exprs/function_call.py +380 -0
  42. pixeltable/exprs/globals.py +69 -0
  43. pixeltable/exprs/image_member_access.py +115 -0
  44. pixeltable/exprs/image_similarity_predicate.py +58 -0
  45. pixeltable/exprs/inline_array.py +107 -0
  46. pixeltable/exprs/inline_dict.py +101 -0
  47. pixeltable/exprs/is_null.py +38 -0
  48. pixeltable/exprs/json_mapper.py +121 -0
  49. pixeltable/exprs/json_path.py +159 -0
  50. pixeltable/exprs/literal.py +54 -0
  51. pixeltable/exprs/object_ref.py +41 -0
  52. pixeltable/exprs/predicate.py +44 -0
  53. pixeltable/exprs/row_builder.py +355 -0
  54. pixeltable/exprs/rowid_ref.py +94 -0
  55. pixeltable/exprs/type_cast.py +53 -0
  56. pixeltable/exprs/variable.py +45 -0
  57. pixeltable/func/__init__.py +9 -0
  58. pixeltable/func/aggregate_function.py +194 -0
  59. pixeltable/func/batched_function.py +53 -0
  60. pixeltable/func/callable_function.py +69 -0
  61. pixeltable/func/expr_template_function.py +82 -0
  62. pixeltable/func/function.py +110 -0
  63. pixeltable/func/function_registry.py +227 -0
  64. pixeltable/func/globals.py +36 -0
  65. pixeltable/func/nos_function.py +202 -0
  66. pixeltable/func/signature.py +166 -0
  67. pixeltable/func/udf.py +163 -0
  68. pixeltable/functions/__init__.py +52 -103
  69. pixeltable/functions/eval.py +216 -0
  70. pixeltable/functions/fireworks.py +34 -0
  71. pixeltable/functions/huggingface.py +120 -0
  72. pixeltable/functions/image.py +16 -0
  73. pixeltable/functions/openai.py +256 -0
  74. pixeltable/functions/pil/image.py +148 -7
  75. pixeltable/functions/string.py +13 -0
  76. pixeltable/functions/together.py +122 -0
  77. pixeltable/functions/util.py +41 -0
  78. pixeltable/functions/video.py +62 -0
  79. pixeltable/iterators/__init__.py +3 -0
  80. pixeltable/iterators/base.py +48 -0
  81. pixeltable/iterators/document.py +311 -0
  82. pixeltable/iterators/video.py +89 -0
  83. pixeltable/metadata/__init__.py +54 -0
  84. pixeltable/metadata/converters/convert_10.py +18 -0
  85. pixeltable/metadata/schema.py +211 -0
  86. pixeltable/plan.py +656 -0
  87. pixeltable/store.py +418 -182
  88. pixeltable/tests/conftest.py +146 -88
  89. pixeltable/tests/functions/test_fireworks.py +42 -0
  90. pixeltable/tests/functions/test_functions.py +60 -0
  91. pixeltable/tests/functions/test_huggingface.py +158 -0
  92. pixeltable/tests/functions/test_openai.py +152 -0
  93. pixeltable/tests/functions/test_together.py +111 -0
  94. pixeltable/tests/test_audio.py +65 -0
  95. pixeltable/tests/test_catalog.py +27 -0
  96. pixeltable/tests/test_client.py +14 -14
  97. pixeltable/tests/test_component_view.py +370 -0
  98. pixeltable/tests/test_dataframe.py +439 -0
  99. pixeltable/tests/test_dirs.py +78 -62
  100. pixeltable/tests/test_document.py +120 -0
  101. pixeltable/tests/test_exprs.py +592 -135
  102. pixeltable/tests/test_function.py +297 -67
  103. pixeltable/tests/test_migration.py +43 -0
  104. pixeltable/tests/test_nos.py +54 -0
  105. pixeltable/tests/test_snapshot.py +208 -0
  106. pixeltable/tests/test_table.py +1195 -263
  107. pixeltable/tests/test_transactional_directory.py +42 -0
  108. pixeltable/tests/test_types.py +5 -11
  109. pixeltable/tests/test_video.py +151 -34
  110. pixeltable/tests/test_view.py +530 -0
  111. pixeltable/tests/utils.py +320 -45
  112. pixeltable/tool/create_test_db_dump.py +149 -0
  113. pixeltable/tool/create_test_video.py +81 -0
  114. pixeltable/type_system.py +445 -124
  115. pixeltable/utils/__init__.py +17 -46
  116. pixeltable/utils/arrow.py +98 -0
  117. pixeltable/utils/clip.py +12 -15
  118. pixeltable/utils/coco.py +136 -0
  119. pixeltable/utils/documents.py +39 -0
  120. pixeltable/utils/filecache.py +195 -0
  121. pixeltable/utils/help.py +11 -0
  122. pixeltable/utils/hf_datasets.py +157 -0
  123. pixeltable/utils/media_store.py +76 -0
  124. pixeltable/utils/parquet.py +167 -0
  125. pixeltable/utils/pytorch.py +91 -0
  126. pixeltable/utils/s3.py +13 -0
  127. pixeltable/utils/sql.py +17 -0
  128. pixeltable/utils/transactional_directory.py +35 -0
  129. pixeltable-0.2.4.dist-info/LICENSE +18 -0
  130. pixeltable-0.2.4.dist-info/METADATA +127 -0
  131. pixeltable-0.2.4.dist-info/RECORD +132 -0
  132. {pixeltable-0.1.0.dist-info → pixeltable-0.2.4.dist-info}/WHEEL +1 -1
  133. pixeltable/catalog.py +0 -1421
  134. pixeltable/exprs.py +0 -1745
  135. pixeltable/function.py +0 -269
  136. pixeltable/functions/clip.py +0 -10
  137. pixeltable/functions/pil/__init__.py +0 -23
  138. pixeltable/functions/tf.py +0 -21
  139. pixeltable/index.py +0 -57
  140. pixeltable/tests/test_dict.py +0 -24
  141. pixeltable/tests/test_functions.py +0 -11
  142. pixeltable/tests/test_tf.py +0 -69
  143. pixeltable/tf.py +0 -33
  144. pixeltable/utils/tf.py +0 -33
  145. pixeltable/utils/video.py +0 -32
  146. pixeltable-0.1.0.dist-info/METADATA +0 -34
  147. pixeltable-0.1.0.dist-info/RECORD +0 -36
pixeltable/client.py CHANGED
@@ -1,44 +1,604 @@
1
- from typing import List, Dict
1
+ from typing import List, Optional, Dict, Type, Any, Union
2
+ import pandas as pd
3
+ import logging
4
+ import dataclasses
2
5
 
6
+ import sqlalchemy as sql
3
7
  import sqlalchemy.orm as orm
4
8
 
5
- from pixeltable import catalog, store
9
+ import pixeltable
10
+ from pixeltable.metadata import schema
6
11
  from pixeltable.env import Env
12
+ import pixeltable.func as func
13
+ import pixeltable.catalog as catalog
14
+ from pixeltable import exceptions as excs
15
+ from pixeltable.exprs import Predicate
16
+ from pixeltable.iterators import ComponentIterator
17
+
18
+ from typing import TYPE_CHECKING
19
+ if TYPE_CHECKING:
20
+ import datasets
7
21
 
8
22
  __all__ = [
9
23
  'Client',
10
24
  ]
11
25
 
12
26
 
27
+ _logger = logging.getLogger('pixeltable')
28
+
13
29
  class Client:
14
- """Missing docstring.
15
30
  """
31
+ Client for interacting with a Pixeltable environment.
32
+ """
33
+
34
+ def __init__(self, reload: bool = False) -> None:
35
+ """Constructs a client.
36
+ """
37
+ env = Env.get()
38
+ env.set_up()
39
+ env.upgrade_metadata()
40
+ if reload:
41
+ catalog.Catalog.clear()
42
+ self.catalog = catalog.Catalog.get()
43
+
44
+ def logging(
45
+ self, *, to_stdout: Optional[bool] = None, level: Optional[int] = None,
46
+ add: Optional[str] = None, remove: Optional[str] = None
47
+ ) -> None:
48
+ """Configure logging.
49
+
50
+ Args:
51
+ to_stdout: if True, also log to stdout
52
+ level: default log level
53
+ add: comma-separated list of 'module name:log level' pairs; ex.: add='video:10'
54
+ remove: comma-separated list of module names
55
+ """
56
+ if to_stdout is not None:
57
+ Env.get().log_to_stdout(to_stdout)
58
+ if level is not None:
59
+ Env.get().set_log_level(level)
60
+ if add is not None:
61
+ for module, level in [t.split(':') for t in add.split(',')]:
62
+ Env.get().set_module_log_level(module, int(level))
63
+ if remove is not None:
64
+ for module in remove.split(','):
65
+ Env.get().set_module_log_level(module, None)
66
+ if to_stdout is None and level is None and add is None and remove is None:
67
+ Env.get().print_log_config()
68
+
69
+ def list_functions(self) -> pd.DataFrame:
70
+ """Returns information about all registered functions.
71
+
72
+ Returns:
73
+ Pandas DataFrame with columns 'Path', 'Name', 'Parameters', 'Return Type', 'Is Agg', 'Library'
74
+ """
75
+ functions = func.FunctionRegistry.get().list_functions()
76
+ paths = ['.'.join(f.self_path.split('.')[:-1]) for f in functions]
77
+ names = [f.name for f in functions]
78
+ params = [
79
+ ', '.join(
80
+ [param_name + ': ' + str(param_type) for param_name, param_type in f.signature.parameters.items()])
81
+ for f in functions
82
+ ]
83
+ pd_df = pd.DataFrame({
84
+ 'Path': paths,
85
+ 'Function Name': names,
86
+ 'Parameters': params,
87
+ 'Return Type': [str(f.signature.get_return_type()) for f in functions],
88
+ })
89
+ pd_df = pd_df.style.set_properties(**{'text-align': 'left'}) \
90
+ .set_table_styles([dict(selector='th', props=[('text-align', 'center')])]) # center-align headings
91
+ return pd_df.hide(axis='index')
92
+
93
+ def get_path(self, schema_obj: catalog.SchemaObject) -> str:
94
+ """Returns the path to a SchemaObject.
95
+
96
+ Args:
97
+ schema_obj: SchemaObject to get the path for.
98
+
99
+ Returns:
100
+ Path to the SchemaObject.
101
+ """
102
+ path_elements: List[str] = []
103
+ dir_id = schema_obj._dir_id
104
+ while dir_id is not None:
105
+ dir = self.catalog.paths.get_schema_obj(dir_id)
106
+ if dir._dir_id is None:
107
+ # this is the root dir with name '', which we don't want to include in the path
108
+ break
109
+ path_elements.insert(0, dir._name)
110
+ dir_id = dir._dir_id
111
+ path_elements.append(schema_obj._name)
112
+ return '.'.join(path_elements)
113
+
114
+ def create_table(
115
+ self, path_str: str, schema: Dict[str, Any], primary_key: Optional[Union[str, List[str]]] = None,
116
+ num_retained_versions: int = 10, comment: str = ''
117
+ ) -> catalog.InsertableTable:
118
+ """Create a new `InsertableTable`.
16
119
 
17
- def __init__(self) -> None:
18
- self.db_cache: Dict[str, catalog.Db] = {}
19
- Env.get().set_up()
20
-
21
- def create_db(self, name: str) -> catalog.Db:
22
- db = catalog.Db.create(name)
23
- self.db_cache[name] = db
24
- return db
25
-
26
- def drop_db(self, name: str, force: bool = False) -> None:
27
- if not force:
28
- return
29
- if name in self.db_cache:
30
- self.db_cache[name].delete()
31
- del self.db_cache[name]
120
+ Args:
121
+ path_str: Path to the table.
122
+ schema: dictionary mapping column names to column types, value expressions, or to column specifications.
123
+ num_retained_versions: Number of versions of the table to retain.
124
+
125
+ Returns:
126
+ The newly created table.
127
+
128
+ Raises:
129
+ Error: if the path already exists or is invalid.
130
+
131
+ Examples:
132
+ Create a table with an int and a string column:
133
+
134
+ >>> table = cl.create_table('my_table', schema={'col1': IntType(), 'col2': StringType()})
135
+
136
+ Create a table with a single indexed image column:
137
+
138
+ >>> table = cl.create_table('my_table', schema={'col1': {'type': ImageType(), 'indexed': True}})
139
+ """
140
+ path = catalog.Path(path_str)
141
+ self.catalog.paths.check_is_valid(path, expected=None)
142
+ dir = self.catalog.paths[path.parent]
143
+
144
+ if len(schema) == 0:
145
+ raise excs.Error(f'Table schema is empty: `{path_str}`')
146
+
147
+ if primary_key is None:
148
+ primary_key = []
149
+ elif isinstance(primary_key, str):
150
+ primary_key = [primary_key]
32
151
  else:
33
- catalog.Db.load(name).delete()
34
-
35
- def get_db(self, name: str) -> catalog.Db:
36
- if name in self.db_cache:
37
- return self.db_cache[name]
38
- db = catalog.Db.load(name)
39
- self.db_cache[name] = db
40
- return db
41
-
42
- def list_dbs(self) -> List[str]:
43
- with orm.Session(store.engine) as session:
44
- return [r[0] for r in session.query(store.Db.name)]
152
+ if not isinstance(primary_key, list) or not all(isinstance(pk, str) for pk in primary_key):
153
+ raise excs.Error('primary_key must be a single column name or a list of column names')
154
+
155
+ tbl = catalog.InsertableTable.create(
156
+ dir._id, path.name, schema, primary_key=primary_key, num_retained_versions=num_retained_versions, comment=comment)
157
+ self.catalog.paths[path] = tbl
158
+ _logger.info(f'Created table `{path_str}`.')
159
+ return tbl
160
+
161
+ def import_parquet(
162
+ self,
163
+ table_path: str,
164
+ *,
165
+ parquet_path: str,
166
+ schema_override: Optional[Dict[str, Any]] = None,
167
+ **kwargs,
168
+ ) -> catalog.InsertableTable:
169
+ """Create a new `InsertableTable` from a Parquet file or set of files. Requires pyarrow to be installed.
170
+ Args:
171
+ path_str: Path to the table within pixeltable.
172
+ parquet_path: Path to an individual Parquet file or directory of Parquet files.
173
+ schema_override: Optional dictionary mapping column names to column type to override the default
174
+ schema inferred from the Parquet file. The column type should be a pixeltable ColumnType.
175
+ For example, {'col_vid': VideoType()}, rather than {'col_vid': StringType()}.
176
+ Any fields not provided explicitly will map to types with `pixeltable.utils.parquet.parquet_schema_to_pixeltable_schema`
177
+ kwargs: Additional arguments to pass to `Client.create_table`.
178
+
179
+ Returns:
180
+ The newly created table. The table will have loaded the data from the Parquet file(s).
181
+ """
182
+ from pixeltable.utils import parquet
183
+
184
+ return parquet.import_parquet(
185
+ self,
186
+ table_path=table_path,
187
+ parquet_path=parquet_path,
188
+ schema_override=schema_override,
189
+ **kwargs,
190
+ )
191
+
192
+ def import_huggingface_dataset(
193
+ self,
194
+ table_path: str,
195
+ dataset: Union['datasets.Dataset', 'datasets.DatasetDict'],
196
+ *,
197
+ column_name_for_split: Optional[str] = 'split',
198
+ schema_override: Optional[Dict[str, Any]] = None,
199
+ **kwargs
200
+ ) -> catalog.InsertableTable:
201
+ """Create a new `InsertableTable` from a Huggingface dataset, or dataset dict with multiple splits.
202
+ Requires datasets library to be installed.
203
+
204
+ Args:
205
+ path_str: Path to the table.
206
+ dataset: Huggingface datasts.Dataset or datasts.DatasetDict to insert into the table.
207
+ column_name_for_split: column name to use for split information. If None, no split information will be stored.
208
+ schema_override: Optional dictionary mapping column names to column type to override the corresponding defaults from
209
+ `pixeltable.utils.hf_datasets.huggingface_schema_to_pixeltable_schema`. The column type should be a pixeltable ColumnType.
210
+ For example, {'col_vid': VideoType()}, rather than {'col_vid': StringType()}.
211
+
212
+ kwargs: Additional arguments to pass to `create_table`.
213
+
214
+ Returns:
215
+ The newly created table. The table will have loaded the data from the dataset.
216
+ """
217
+ from pixeltable.utils import hf_datasets
218
+
219
+ return hf_datasets.import_huggingface_dataset(
220
+ self,
221
+ table_path,
222
+ dataset,
223
+ column_name_for_split=column_name_for_split,
224
+ schema_override=schema_override,
225
+ **kwargs,
226
+ )
227
+
228
+ def create_view(
229
+ self, path_str: str, base: catalog.Table, *, schema: Optional[Dict[str, Any]] = None,
230
+ filter: Optional[Predicate] = None,
231
+ is_snapshot: bool = False, iterator_class: Optional[Type[ComponentIterator]] = None,
232
+ iterator_args: Optional[Dict[str, Any]] = None, num_retained_versions: int = 10, comment: str = '',
233
+ ignore_errors: bool = False) -> catalog.View:
234
+ """Create a new `View`.
235
+
236
+ Args:
237
+ path_str: Path to the view.
238
+ base: Table (ie, table or view or snapshot) to base the view on.
239
+ schema: dictionary mapping column names to column types, value expressions, or to column specifications.
240
+ filter: Predicate to filter rows of the base table.
241
+ is_snapshot: Whether the view is a snapshot.
242
+ iterator_class: Class of the iterator to use for the view.
243
+ iterator_args: Arguments to pass to the iterator class.
244
+ num_retained_versions: Number of versions of the view to retain.
245
+ ignore_errors: if True, fail silently if the path already exists or is invalid.
246
+
247
+ Returns:
248
+ The newly created view.
249
+
250
+ Raises:
251
+ Error: if the path already exists or is invalid.
252
+
253
+ Examples:
254
+ Create a view with an additional int and a string column and a filter:
255
+
256
+ >>> view = cl.create_view(
257
+ 'my_view', base, schema={'col3': IntType(), 'col4': StringType()}, filter=base.col1 > 10)
258
+
259
+ Create a table snapshot:
260
+
261
+ >>> snapshot_view = cl.create_view('my_snapshot_view', base, is_snapshot=True)
262
+
263
+ Create an immutable view with additional computed columns and a filter:
264
+
265
+ >>> snapshot_view = cl.create_view(
266
+ 'my_snapshot', base, schema={'col3': base.col2 + 1}, filter=base.col1 > 10, is_snapshot=True)
267
+ """
268
+ assert (iterator_class is None) == (iterator_args is None)
269
+ assert isinstance(base, catalog.Table)
270
+ path = catalog.Path(path_str)
271
+ try:
272
+ self.catalog.paths.check_is_valid(path, expected=None)
273
+ except Exception as e:
274
+ if ignore_errors:
275
+ return
276
+ else:
277
+ raise e
278
+ dir = self.catalog.paths[path.parent]
279
+
280
+ if schema is None:
281
+ schema = {}
282
+ view = catalog.View.create(
283
+ dir._id, path.name, base=base, schema=schema, predicate=filter, is_snapshot=is_snapshot,
284
+ iterator_cls=iterator_class, iterator_args=iterator_args, num_retained_versions=num_retained_versions, comment=comment)
285
+ self.catalog.paths[path] = view
286
+ _logger.info(f'Created view `{path_str}`.')
287
+ return view
288
+
289
+ def get_table(self, path: str) -> catalog.Table:
290
+ """Get a handle to a table (including views and snapshots).
291
+
292
+ Args:
293
+ path: Path to the table.
294
+
295
+ Returns:
296
+ A `InsertableTable` or `View` object.
297
+
298
+ Raises:
299
+ Error: If the path does not exist or does not designate a table.
300
+
301
+ Examples:
302
+ Get handle for a table in the top-level directory:
303
+
304
+ >>> table = cl.get_table('my_table')
305
+
306
+ For a table in a subdirectory:
307
+
308
+ >>> table = cl.get_table('subdir.my_table')
309
+
310
+ For a snapshot in the top-level directory:
311
+
312
+ >>> table = cl.get_table('my_snapshot')
313
+ """
314
+ p = catalog.Path(path)
315
+ self.catalog.paths.check_is_valid(p, expected=catalog.Table)
316
+ obj = self.catalog.paths[p]
317
+ return obj
318
+
319
+ def move(self, path: str, new_path: str) -> None:
320
+ """Move a schema object to a new directory and/or rename a schema object.
321
+
322
+ Args:
323
+ path: absolute path to the existing schema object.
324
+ new_path: absolute new path for the schema object.
325
+
326
+ Raises:
327
+ Error: If path does not exist or new_path already exists.
328
+
329
+ Examples:
330
+ Move a table to a different directory:
331
+
332
+ >>>> cl.move('dir1.my_table', 'dir2.my_table')
333
+
334
+ Rename a table:
335
+
336
+ >>>> cl.move('dir1.my_table', 'dir1.new_name')
337
+ """
338
+ p = catalog.Path(path)
339
+ self.catalog.paths.check_is_valid(p, expected=catalog.SchemaObject)
340
+ new_p = catalog.Path(new_path)
341
+ self.catalog.paths.check_is_valid(new_p, expected=None)
342
+ obj = self.catalog.paths[p]
343
+ self.catalog.paths.move(p, new_p)
344
+ new_dir = self.catalog.paths[new_p.parent]
345
+ obj.move(new_p.name, new_dir._id)
346
+
347
+ def list_tables(self, dir_path: str = '', recursive: bool = True) -> List[str]:
348
+ """List the tables in a directory.
349
+
350
+ Args:
351
+ dir_path: Path to the directory. Defaults to the root directory.
352
+ recursive: Whether to list tables in subdirectories as well.
353
+
354
+ Returns:
355
+ A list of table paths.
356
+
357
+ Raises:
358
+ Error: If the path does not exist or does not designate a directory.
359
+
360
+ Examples:
361
+ List tables in top-level directory:
362
+
363
+ >>> cl.list_tables()
364
+ ['my_table', ...]
365
+
366
+ List tables in 'dir1':
367
+
368
+ >>> cl.list_tables('dir1')
369
+ [...]
370
+ """
371
+ assert dir_path is not None
372
+ path = catalog.Path(dir_path, empty_is_valid=True)
373
+ self.catalog.paths.check_is_valid(path, expected=catalog.Dir)
374
+ return [str(p) for p in self.catalog.paths.get_children(path, child_type=catalog.Table, recursive=recursive)]
375
+
376
+ def drop_table(self, path: str, force: bool = False, ignore_errors: bool = False) -> None:
377
+ """Drop a table.
378
+
379
+ Args:
380
+ path: Path to the table.
381
+ force: Whether to drop the table even if it has unsaved changes.
382
+ ignore_errors: Whether to ignore errors if the table does not exist.
383
+
384
+ Raises:
385
+ Error: If the path does not exist or does not designate a table and ignore_errors is False.
386
+
387
+ Examples:
388
+ >>> cl.drop_table('my_table')
389
+ """
390
+ path_obj = catalog.Path(path)
391
+ try:
392
+ self.catalog.paths.check_is_valid(path_obj, expected=catalog.Table)
393
+ except Exception as e:
394
+ if ignore_errors:
395
+ _logger.info(f'Skipped table `{path}` (does not exist).')
396
+ return
397
+ else:
398
+ raise e
399
+ tbl = self.catalog.paths[path_obj]
400
+ if len(self.catalog.tbl_dependents[tbl._id]) > 0:
401
+ dependent_paths = [self.get_path(dep) for dep in self.catalog.tbl_dependents[tbl._id]]
402
+ raise excs.Error(f'Table {path} has dependents: {", ".join(dependent_paths)}')
403
+ tbl._drop()
404
+ del self.catalog.paths[path_obj]
405
+ _logger.info(f'Dropped table `{path}`.')
406
+
407
+ def create_dir(self, path_str: str, ignore_errors: bool = False) -> None:
408
+ """Create a directory.
409
+
410
+ Args:
411
+ path_str: Path to the directory.
412
+ ignore_errors: if True, silently returns on error
413
+
414
+ Raises:
415
+ Error: If the path already exists or the parent is not a directory.
416
+
417
+ Examples:
418
+ >>> cl.create_dir('my_dir')
419
+
420
+ Create a subdirectory:
421
+
422
+ >>> cl.create_dir('my_dir.sub_dir')
423
+ """
424
+ try:
425
+ path = catalog.Path(path_str)
426
+ self.catalog.paths.check_is_valid(path, expected=None)
427
+ parent = self.catalog.paths[path.parent]
428
+ assert parent is not None
429
+ with orm.Session(Env.get().engine, future=True) as session:
430
+ dir_md = schema.DirMd(name=path.name)
431
+ dir_record = schema.Dir(parent_id=parent._id, md=dataclasses.asdict(dir_md))
432
+ session.add(dir_record)
433
+ session.flush()
434
+ assert dir_record.id is not None
435
+ self.catalog.paths[path] = catalog.Dir(dir_record.id, parent._id, path.name)
436
+ session.commit()
437
+ _logger.info(f'Created directory `{path_str}`.')
438
+ print(f'Created directory `{path_str}`.')
439
+ except excs.Error as e:
440
+ if ignore_errors:
441
+ return
442
+ else:
443
+ raise e
444
+
445
+ def rm_dir(self, path_str: str) -> None:
446
+ """Remove a directory.
447
+
448
+ Args:
449
+ path_str: Path to the directory.
450
+
451
+ Raises:
452
+ Error: If the path does not exist or does not designate a directory or if the directory is not empty.
453
+
454
+ Examples:
455
+ >>> cl.rm_dir('my_dir')
456
+
457
+ Remove a subdirectory:
458
+
459
+ >>> cl.rm_dir('my_dir.sub_dir')
460
+ """
461
+ path = catalog.Path(path_str)
462
+ self.catalog.paths.check_is_valid(path, expected=catalog.Dir)
463
+
464
+ # make sure it's empty
465
+ if len(self.catalog.paths.get_children(path, child_type=None, recursive=True)) > 0:
466
+ raise excs.Error(f'Directory {path_str} is not empty')
467
+ # TODO: figure out how to make force=True work in the presence of snapshots
468
+ # # delete tables
469
+ # for tbl_path in self.paths.get_children(path, child_type=MutableTable, recursive=True):
470
+ # self.drop_table(str(tbl_path), force=True)
471
+ # # rm subdirs
472
+ # for dir_path in self.paths.get_children(path, child_type=Dir, recursive=False):
473
+ # self.rm_dir(str(dir_path), force=True)
474
+
475
+ with Env.get().engine.begin() as conn:
476
+ dir = self.catalog.paths[path]
477
+ conn.execute(sql.delete(schema.Dir.__table__).where(schema.Dir.id == dir._id))
478
+ del self.catalog.paths[path]
479
+ _logger.info(f'Removed directory {path_str}')
480
+
481
+ def list_dirs(self, path_str: str = '', recursive: bool = True) -> List[str]:
482
+ """List the directories in a directory.
483
+
484
+ Args:
485
+ path_str: Path to the directory.
486
+ recursive: Whether to list subdirectories recursively.
487
+
488
+ Returns:
489
+ List of directory paths.
490
+
491
+ Raises:
492
+ Error: If the path does not exist or does not designate a directory.
493
+
494
+ Examples:
495
+ >>> cl.list_dirs('my_dir', recursive=True)
496
+ ['my_dir', 'my_dir.sub_dir1']
497
+ """
498
+ path = catalog.Path(path_str, empty_is_valid=True)
499
+ self.catalog.paths.check_is_valid(path, expected=catalog.Dir)
500
+ return [str(p) for p in self.catalog.paths.get_children(path, child_type=catalog.Dir, recursive=recursive)]
501
+
502
+ # TODO: for now, named functions are deprecated, until we understand the use case and requirements better
503
+ # def create_function(self, path_str: str, fn: func.Function) -> None:
504
+ # """Create a stored function.
505
+ #
506
+ # Args:
507
+ # path_str: path where the function gets stored
508
+ # func: previously created Function object
509
+ #
510
+ # Raises:
511
+ # Error: if the path already exists or the parent is not a directory
512
+ #
513
+ # Examples:
514
+ # Create a function ``detect()`` that takes an image and returns a JSON object, and store it in ``my_dir``:
515
+ #
516
+ # >>> @pxt.udf(param_types=[ImageType()], return_type=JsonType())
517
+ # ... def detect(img):
518
+ # ... ...
519
+ # >>> cl.create_function('my_dir.detect', detect)
520
+ # """
521
+ # if fn.is_module_function:
522
+ # raise excs.Error(f'Cannot create a named function for a library function')
523
+ # path = catalog.Path(path_str)
524
+ # self.catalog.paths.check_is_valid(path, expected=None)
525
+ # dir = self.catalog.paths[path.parent]
526
+ #
527
+ # func.FunctionRegistry.get().create_function(fn, dir._id, path.name)
528
+ # self.catalog.paths[path] = catalog.NamedFunction(fn.id, dir._id, path.name)
529
+ # fn.md.fqn = str(path)
530
+ # _logger.info(f'Created function {path_str}')
531
+ #
532
+ # def update_function(self, path_str: str, fn: func.Function) -> None:
533
+ # """Update the implementation of a stored function.
534
+ #
535
+ # Args:
536
+ # path_str: path to the function to be updated
537
+ # func: new function implementation
538
+ #
539
+ # Raises:
540
+ # Error: if the path does not exist or ``func`` has a different signature than the stored function.
541
+ # """
542
+ # if fn.is_module_function:
543
+ # raise excs.Error(f'Cannot update a named function to a library function')
544
+ # path = catalog.Path(path_str)
545
+ # self.catalog.paths.check_is_valid(path, expected=catalog.NamedFunction)
546
+ # named_fn = self.catalog.paths[path]
547
+ # f = func.FunctionRegistry.get().get_function(id=named_fn._id)
548
+ # if f.md.signature != fn.md.signature:
549
+ # raise excs.Error(
550
+ # f'The function signature cannot be changed. The existing signature is {f.md.signature}')
551
+ # if f.is_aggregate != fn.is_aggregate:
552
+ # raise excs.Error(f'Cannot change an aggregate function into a non-aggregate function and vice versa')
553
+ # func.FunctionRegistry.get().update_function(named_fn._id, fn)
554
+ # _logger.info(f'Updated function {path_str}')
555
+ #
556
+ # def get_function(self, path_str: str) -> func.Function:
557
+ # """Get a handle to a stored function.
558
+ #
559
+ # Args:
560
+ # path_str: path to the function
561
+ #
562
+ # Returns:
563
+ # Function object
564
+ #
565
+ # Raises:
566
+ # Error: if the path does not exist or is not a function
567
+ #
568
+ # Examples:
569
+ # >>> detect = cl.get_function('my_dir.detect')
570
+ # """
571
+ # path = catalog.Path(path_str)
572
+ # self.catalog.paths.check_is_valid(path, expected=catalog.NamedFunction)
573
+ # named_fn = self.catalog.paths[path]
574
+ # assert isinstance(named_fn, catalog.NamedFunction)
575
+ # fn = func.FunctionRegistry.get().get_function(id=named_fn._id)
576
+ # fn.md.fqn = str(path)
577
+ # return fn
578
+ #
579
+ # def drop_function(self, path_str: str, ignore_errors: bool = False) -> None:
580
+ # """Deletes stored function.
581
+ #
582
+ # Args:
583
+ # path_str: path to the function
584
+ # ignore_errors: if True, does not raise if the function does not exist
585
+ #
586
+ # Raises:
587
+ # Error: if the path does not exist or is not a function
588
+ #
589
+ # Examples:
590
+ # >>> cl.drop_function('my_dir.detect')
591
+ # """
592
+ # path = catalog.Path(path_str)
593
+ # try:
594
+ # self.catalog.paths.check_is_valid(path, expected=catalog.NamedFunction)
595
+ # except excs.Error as e:
596
+ # if ignore_errors:
597
+ # return
598
+ # else:
599
+ # raise e
600
+ # named_fn = self.catalog.paths[path]
601
+ # func.FunctionRegistry.get().delete_function(named_fn._id)
602
+ # del self.catalog.paths[path]
603
+ # _logger.info(f'Dropped function {path_str}')
604
+