mostlyai 4.4.5__tar.gz → 4.4.6__tar.gz

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 (85) hide show
  1. {mostlyai-4.4.5 → mostlyai-4.4.6}/PKG-INFO +9 -7
  2. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/__init__.py +1 -1
  3. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/base.py +10 -0
  4. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/db/base.py +10 -1
  5. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/file/base.py +32 -1
  6. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/file/container/aws.py +39 -6
  7. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/file/container/azure.py +21 -0
  8. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/file/container/gcs.py +6 -0
  9. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/util/common.py +95 -0
  10. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/connectors.py +11 -0
  11. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/routes.py +21 -2
  12. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/client/connectors.py +15 -0
  13. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/domain.py +25 -2
  14. {mostlyai-4.4.5 → mostlyai-4.4.6}/pyproject.toml +9 -7
  15. {mostlyai-4.4.5 → mostlyai-4.4.6}/.gitignore +0 -0
  16. {mostlyai-4.4.5 → mostlyai-4.4.6}/LICENSE +0 -0
  17. {mostlyai-4.4.5 → mostlyai-4.4.6}/README.md +0 -0
  18. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/__init__.py +0 -0
  19. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/auto_detect.py +0 -0
  20. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/context.py +0 -0
  21. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/conversions.py +0 -0
  22. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/db/__init__.py +0 -0
  23. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/db/bigquery.py +0 -0
  24. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/db/databricks.py +0 -0
  25. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/db/hive.py +0 -0
  26. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/db/mssql.py +0 -0
  27. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/db/mysql.py +0 -0
  28. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/db/oracle.py +0 -0
  29. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/db/postgresql.py +0 -0
  30. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/db/snowflake.py +0 -0
  31. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/db/sqlite.py +0 -0
  32. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/db/types_coercion.py +0 -0
  33. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/dtype.py +0 -0
  34. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/exceptions.py +0 -0
  35. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/file/__init__.py +0 -0
  36. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/file/container/__init__.py +0 -0
  37. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/file/container/bucket_based.py +0 -0
  38. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/file/container/minio.py +0 -0
  39. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/file/table/__init__.py +0 -0
  40. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/file/table/csv.py +0 -0
  41. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/file/table/feather.py +0 -0
  42. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/file/table/json.py +0 -0
  43. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/file/table/parquet.py +0 -0
  44. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/file/utils.py +0 -0
  45. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/language_model.py +0 -0
  46. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/metadata_objects.py +0 -0
  47. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/non_context.py +0 -0
  48. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/progress_callback.py +0 -0
  49. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/pull.py +0 -0
  50. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/pull_context.py +0 -0
  51. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/pull_utils.py +0 -0
  52. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/push.py +0 -0
  53. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/util/__init__.py +0 -0
  54. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_data/util/kerberos.py +0 -0
  55. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/__init__.py +0 -0
  56. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/cli.py +0 -0
  57. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/execution/__init__.py +0 -0
  58. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/execution/jobs.py +0 -0
  59. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/execution/plan.py +0 -0
  60. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/execution/step_analyze_training_data.py +0 -0
  61. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/execution/step_create_data_report.py +0 -0
  62. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/execution/step_create_model_report.py +0 -0
  63. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/execution/step_deliver_data.py +0 -0
  64. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/execution/step_encode_training_data.py +0 -0
  65. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/execution/step_finalize_generation.py +0 -0
  66. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/execution/step_finalize_training.py +0 -0
  67. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/execution/step_generate_data.py +0 -0
  68. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/execution/step_generate_model_report_data.py +0 -0
  69. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/execution/step_pull_training_data.py +0 -0
  70. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/execution/step_train_model.py +0 -0
  71. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/generators.py +0 -0
  72. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/progress.py +0 -0
  73. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/server.py +0 -0
  74. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/storage.py +0 -0
  75. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/_local/synthetic_datasets.py +0 -0
  76. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/client/__init__.py +0 -0
  77. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/client/_base_utils.py +0 -0
  78. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/client/_naming_conventions.py +0 -0
  79. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/client/_utils.py +0 -0
  80. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/client/api.py +0 -0
  81. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/client/base.py +0 -0
  82. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/client/exceptions.py +0 -0
  83. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/client/generators.py +0 -0
  84. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/client/synthetic_datasets.py +0 -0
  85. {mostlyai-4.4.5 → mostlyai-4.4.6}/mostlyai/sdk/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mostlyai
3
- Version: 4.4.5
3
+ Version: 4.4.6
4
4
  Summary: Synthetic Data SDK
5
5
  Project-URL: homepage, https://app.mostly.ai/
6
6
  Project-URL: repository, https://github.com/mostly-ai/mostlyai
@@ -24,6 +24,7 @@ Classifier: Programming Language :: Python :: 3.13
24
24
  Classifier: Topic :: Software Development :: Libraries
25
25
  Classifier: Typing :: Typed
26
26
  Requires-Python: <3.14,>=3.10
27
+ Requires-Dist: duckdb>=1.2.1
27
28
  Requires-Dist: environs>=9.5.0
28
29
  Requires-Dist: greenlet<4,>=3.1.1
29
30
  Requires-Dist: gunicorn>=23.0.0
@@ -39,6 +40,7 @@ Requires-Dist: rich>=13.7.0
39
40
  Requires-Dist: schema>=0.7.5
40
41
  Requires-Dist: semantic-version>=2.10.0
41
42
  Requires-Dist: smart-open>=6.0.0
43
+ Requires-Dist: sqlparse>=0.5.3
42
44
  Requires-Dist: typer>=0.9.0
43
45
  Requires-Dist: xxhash>=3.2.0
44
46
  Provides-Extra: databricks
@@ -57,8 +59,8 @@ Requires-Dist: fastapi<0.116,>=0.115.6; extra == 'local'
57
59
  Requires-Dist: filelock>=3.16.1; extra == 'local'
58
60
  Requires-Dist: gcsfs>=2023.1.0; extra == 'local'
59
61
  Requires-Dist: joblib>=1.2.0; extra == 'local'
60
- Requires-Dist: mostlyai-engine==1.1.10; extra == 'local'
61
- Requires-Dist: mostlyai-qa==1.5.11; extra == 'local'
62
+ Requires-Dist: mostlyai-engine==1.1.11; extra == 'local'
63
+ Requires-Dist: mostlyai-qa==1.5.12; extra == 'local'
62
64
  Requires-Dist: networkx<4,>=3.0; extra == 'local'
63
65
  Requires-Dist: openpyxl>=3.1.5; extra == 'local'
64
66
  Requires-Dist: python-multipart>=0.0.20; extra == 'local'
@@ -80,8 +82,8 @@ Requires-Dist: fastapi<0.116,>=0.115.6; extra == 'local-cpu'
80
82
  Requires-Dist: filelock>=3.16.1; extra == 'local-cpu'
81
83
  Requires-Dist: gcsfs>=2023.1.0; extra == 'local-cpu'
82
84
  Requires-Dist: joblib>=1.2.0; extra == 'local-cpu'
83
- Requires-Dist: mostlyai-engine[cpu]==1.1.10; extra == 'local-cpu'
84
- Requires-Dist: mostlyai-qa[cpu]==1.5.11; extra == 'local-cpu'
85
+ Requires-Dist: mostlyai-engine[cpu]==1.1.11; extra == 'local-cpu'
86
+ Requires-Dist: mostlyai-qa[cpu]==1.5.12; extra == 'local-cpu'
85
87
  Requires-Dist: networkx<4,>=3.0; extra == 'local-cpu'
86
88
  Requires-Dist: openpyxl>=3.1.5; extra == 'local-cpu'
87
89
  Requires-Dist: python-multipart>=0.0.20; extra == 'local-cpu'
@@ -103,8 +105,8 @@ Requires-Dist: fastapi<0.116,>=0.115.6; extra == 'local-gpu'
103
105
  Requires-Dist: filelock>=3.16.1; extra == 'local-gpu'
104
106
  Requires-Dist: gcsfs>=2023.1.0; extra == 'local-gpu'
105
107
  Requires-Dist: joblib>=1.2.0; extra == 'local-gpu'
106
- Requires-Dist: mostlyai-engine[gpu]==1.1.10; extra == 'local-gpu'
107
- Requires-Dist: mostlyai-qa[gpu]==1.5.11; extra == 'local-gpu'
108
+ Requires-Dist: mostlyai-engine[gpu]==1.1.11; extra == 'local-gpu'
109
+ Requires-Dist: mostlyai-qa[gpu]==1.5.12; extra == 'local-gpu'
108
110
  Requires-Dist: networkx<4,>=3.0; extra == 'local-gpu'
109
111
  Requires-Dist: openpyxl>=3.1.5; extra == 'local-gpu'
110
112
  Requires-Dist: python-multipart>=0.0.20; extra == 'local-gpu'
@@ -15,4 +15,4 @@
15
15
  from mostlyai.sdk.client.api import MostlyAI
16
16
 
17
17
  __all__ = ["MostlyAI"]
18
- __version__ = "4.4.5" # Do not set this manually. Use poetry version [params].
18
+ __version__ = "4.4.6" # Do not set this manually. Use poetry version [params].
@@ -442,6 +442,16 @@ class DataContainer(abc.ABC):
442
442
  """
443
443
  pass
444
444
 
445
+ @abc.abstractmethod
446
+ def query(self, sql: str) -> pd.DataFrame:
447
+ """
448
+ Execute a SQL query against this data source.
449
+
450
+ :param sql: SQL query to execute
451
+ :return: DataFrame containing the query results
452
+ """
453
+ pass
454
+
445
455
  # DEFAULT METHODS (noop, unless applicable)
446
456
  def drop_all(self):
447
457
  """
@@ -59,7 +59,7 @@ from mostlyai.sdk._data.dtype import (
59
59
  WrappedDType,
60
60
  coerce_dtypes_by_encoding,
61
61
  )
62
- from mostlyai.sdk._data.util.common import prepare_ssl_path, ColumnSort, OrderBy
62
+ from mostlyai.sdk._data.util.common import prepare_ssl_path, ColumnSort, OrderBy, assert_read_only_sql
63
63
  from mostlyai.sdk._data.util.kerberos import is_kerberos_ticket_alive
64
64
  from sqlalchemy import Table
65
65
 
@@ -587,6 +587,15 @@ class SqlAlchemyContainer(DBContainer, abc.ABC):
587
587
  def does_database_exist(self) -> bool:
588
588
  pass
589
589
 
590
+ def query(self, sql: str) -> pd.DataFrame:
591
+ assert_read_only_sql(sql)
592
+ with self.init_sa_connection() as engine:
593
+ try:
594
+ return pd.read_sql(sql, engine)
595
+ except sa.exc.SQLAlchemyError as e:
596
+ _LOG.error(f"Error executing query: {str(e)}")
597
+ raise
598
+
590
599
  def drop_all(self):
591
600
  if self.sa_metadata:
592
601
  with self.use_sa_engine() as sa_engine:
@@ -24,6 +24,7 @@ from typing import Any
24
24
  from collections.abc import Generator, Iterable
25
25
  from urllib.parse import urlparse
26
26
 
27
+ import duckdb
27
28
  import pandas as pd
28
29
  import pyarrow
29
30
  import pyarrow as pa
@@ -38,7 +39,7 @@ from mostlyai.sdk._data.base import (
38
39
  DataTable,
39
40
  order_df_by,
40
41
  )
41
- from mostlyai.sdk._data.util.common import SCHEME_SEP, DATA_TABLE_METADATA_FIELDS, OrderBy
42
+ from mostlyai.sdk._data.util.common import SCHEME_SEP, DATA_TABLE_METADATA_FIELDS, OrderBy, assert_read_only_sql
42
43
  from mostlyai.sdk._data.dtype import (
43
44
  PandasDType,
44
45
  coerce_dtypes_by_encoding,
@@ -493,6 +494,36 @@ class FileContainer(DataContainer):
493
494
  self.set_uri(location)
494
495
  return {"location": location}
495
496
 
497
+ def _init_duckdb(self, con: duckdb.DuckDBPyConnection) -> None:
498
+ pass
499
+
500
+ @staticmethod
501
+ def _create_duckdb_secret(con: duckdb.DuckDBPyConnection, secret_params: dict[str, Any]) -> None:
502
+ def sql_escape(val: str) -> str:
503
+ return str(val).replace("'", "''") # escape single quotes for SQL strings
504
+
505
+ # all values must be wrapped in single quotes and escaped
506
+ parts = [f"{key} '{sql_escape(value)}'" for key, value in secret_params.items()]
507
+ joined_parts = ",\n ".join(parts)
508
+ create_secret_sql = f"CREATE SECRET (\n {joined_parts}\n);"
509
+
510
+ con.execute(create_secret_sql)
511
+
512
+ def query(self, sql: str) -> pd.DataFrame:
513
+ assert_read_only_sql(sql)
514
+ try:
515
+ with duckdb.connect(database=":memory:") as con:
516
+ self._init_duckdb(con)
517
+ result = con.execute(sql).fetchdf()
518
+
519
+ return result
520
+ except duckdb.IOException as e:
521
+ _LOG.error(f"IO Error executing query: {str(e)}")
522
+ raise
523
+ except duckdb.Error as e:
524
+ _LOG.error(f"DuckDB Error executing query: {str(e)}")
525
+ raise
526
+
496
527
 
497
528
  class LocalFileContainer(FileContainer):
498
529
  SCHEMES = ["file"]
@@ -16,10 +16,13 @@ import logging
16
16
  import os
17
17
  import tempfile
18
18
  from typing import Any
19
+ from urllib.parse import urlparse
20
+ import re
19
21
 
20
22
  import boto3 as boto3
21
23
  import s3fs
22
24
  from cloudpathlib.s3 import S3Client, S3Path
25
+ import duckdb
23
26
 
24
27
  from mostlyai.sdk._data.exceptions import MostlyDataException
25
28
  from mostlyai.sdk._data.file.container.bucket_based import BucketBasedContainer
@@ -55,7 +58,12 @@ class AwsS3FileContainer(BucketBasedContainer):
55
58
  if do_decrypt_secret:
56
59
  self.decrypt_secret()
57
60
  self.ca_cert_content = self.decrypt(self.ca_certificate) if self.ssl_enabled and self.ca_certificate else None
58
-
61
+ self.region_name = None
62
+ # extract region from endpoint URL if it's an AWS endpoint
63
+ if self.endpoint_url and ".amazonaws.com" in self.endpoint_url:
64
+ match = re.search(r"s3[.-](.+?)\.amazonaws\.com", self.endpoint_url)
65
+ if match:
66
+ self.region_name = match.group(1)
59
67
  if not (self.secret_key and self.access_key):
60
68
  raise MostlyDataException("Provide the S3 credentials.")
61
69
  boto_session = boto3.Session(
@@ -78,11 +86,8 @@ class AwsS3FileContainer(BucketBasedContainer):
78
86
  else:
79
87
  self.ssl_verify = None
80
88
  client_kwargs = {"verify": self.ssl_verify}
81
- if self.endpoint_url and ".amazonaws.com" in self.endpoint_url:
82
- # aws s3 needs region_name to be set when using custom endpoint
83
- parts = self.endpoint_url.split(".")
84
- if len(parts) > 1:
85
- client_kwargs["region_name"] = parts[1]
89
+ if self.region_name:
90
+ client_kwargs["region_name"] = self.region_name
86
91
  self.fs = s3fs.S3FileSystem(
87
92
  endpoint_url=self.endpoint_url,
88
93
  secret=self.secret_key,
@@ -147,3 +152,31 @@ class AwsS3FileContainer(BucketBasedContainer):
147
152
  raise MostlyDataException("Cannot reach the endpoint URL.")
148
153
  else:
149
154
  raise MostlyDataException(f"Error has occurred: {str(e)}")
155
+
156
+ def _init_duckdb(self, con: duckdb.DuckDBPyConnection) -> None:
157
+ # fallback to con.register_filesystem (instead of DuckDB's httpfs + aws) if:
158
+ # 1. no endpoint is set (defaults to AWS, but region is not specified)
159
+ # 2. it's an amazon endpoint but no region is set
160
+ # 3. CA certificate is being used
161
+ if (
162
+ not self.endpoint_url
163
+ or (self.endpoint_url and ".amazonaws.com" in self.endpoint_url and not self.region_name)
164
+ or (self.ssl_enabled and self.ssl_verify)
165
+ ):
166
+ con.register_filesystem(self.fs)
167
+ return
168
+
169
+ # extract only the hostname (and optional port) from the endpoint URL
170
+ endpoint = urlparse(self.endpoint_url).netloc
171
+ secret_params = {
172
+ "TYPE": "s3",
173
+ "KEY_ID": self.access_key,
174
+ "SECRET": self.secret_key,
175
+ "ENDPOINT": endpoint,
176
+ "USE_SSL": bool(self.ssl_enabled),
177
+ }
178
+
179
+ if self.region_name:
180
+ secret_params["REGION"] = self.region_name
181
+
182
+ self._create_duckdb_secret(con, secret_params)
@@ -22,6 +22,7 @@ from mostlyai.sdk._data.file.container.bucket_based import BucketBasedContainer
22
22
 
23
23
  from azure.identity import ClientSecretCredential
24
24
  from azure.storage.blob import BlobServiceClient
25
+ import duckdb
25
26
 
26
27
 
27
28
  class AzureBlobFileContainer(BucketBasedContainer):
@@ -128,3 +129,23 @@ class AzureBlobFileContainer(BucketBasedContainer):
128
129
  raise MostlyDataException("Client secret is incorrect.")
129
130
  else:
130
131
  raise MostlyDataException(f"Authenticity check failed: {str(e)}")
132
+
133
+ def _init_duckdb(self, con: duckdb.DuckDBPyConnection) -> None:
134
+ if self.account_key:
135
+ # use connection string authentication
136
+ secret_params = {
137
+ "TYPE": "azure",
138
+ "CONNECTION_STRING": f"DefaultEndpointsProtocol=https;AccountName={self.account_name};AccountKey={self.account_key}",
139
+ }
140
+ else:
141
+ # use service principal authentication
142
+ secret_params = {
143
+ "TYPE": "azure",
144
+ "PROVIDER": "service_principal",
145
+ "ACCOUNT_NAME": self.account_name,
146
+ "CLIENT_ID": self.client_id,
147
+ "CLIENT_SECRET": self.client_secret,
148
+ "TENANT_ID": self.tenant_id,
149
+ }
150
+
151
+ self._create_duckdb_secret(con, secret_params)
@@ -18,6 +18,7 @@ from typing import Any
18
18
  import gcsfs
19
19
  from cloudpathlib.gs import GSClient, GSPath
20
20
  from google.cloud import storage
21
+ import duckdb
21
22
 
22
23
  from mostlyai.sdk._data.exceptions import MostlyDataException
23
24
  from mostlyai.sdk._data.file.container.bucket_based import BucketBasedContainer
@@ -72,3 +73,8 @@ class GcsContainer(BucketBasedContainer):
72
73
 
73
74
  def _check_authenticity(self) -> bool:
74
75
  return gcsfs.GCSFileSystem(project=self.key_file["project_id"], token=self.key_file) is not None
76
+
77
+ def _init_duckdb(self, con: duckdb.DuckDBPyConnection) -> None:
78
+ # register the GCS filesystem with DuckDB using service account credentials
79
+ # this is an alternative to HMAC keys, which we don't use
80
+ con.register_filesystem(self.fs)
@@ -27,6 +27,8 @@ import pandas as pd
27
27
  from Cryptodome.Cipher import AES
28
28
  from Cryptodome.Util.Padding import pad, unpad
29
29
  import concurrent.futures
30
+ import sqlparse
31
+ from sqlparse.tokens import DML
30
32
 
31
33
  from mostlyai.sdk._data.exceptions import MostlyDataException
32
34
 
@@ -177,6 +179,99 @@ def strip_column_prefix(
177
179
  return prefixed_data[0] if is_str else prefixed_data
178
180
 
179
181
 
182
+ def assert_read_only_sql(sql: str) -> None:
183
+ # define allowed read-only operations
184
+ read_only_dml = {"select", "with", "show", "describe", "explain"}
185
+
186
+ # define disallowed operations that should be blocked
187
+ disallowed_operations = {
188
+ # data manipulation language (DML)
189
+ "insert",
190
+ "update",
191
+ "delete",
192
+ "merge",
193
+ "replace",
194
+ # data definition language (DDL)
195
+ "create",
196
+ "alter",
197
+ "drop",
198
+ "truncate",
199
+ "rename",
200
+ # data control language (DCL)
201
+ "grant",
202
+ "revoke",
203
+ "deny",
204
+ # transaction control language (TCL)
205
+ "commit",
206
+ "rollback",
207
+ "savepoint",
208
+ # other dangerous operations
209
+ "set",
210
+ "use",
211
+ "exec",
212
+ "execute",
213
+ "call",
214
+ "declare",
215
+ "begin",
216
+ "end",
217
+ "backup",
218
+ "restore",
219
+ "load",
220
+ "import",
221
+ "export",
222
+ "copy",
223
+ "analyze",
224
+ "vacuum",
225
+ "optimize",
226
+ "repair",
227
+ "check",
228
+ "checkpoint",
229
+ }
230
+
231
+ # handle empty statements
232
+ if not sql or sql.strip() in {"", ";", "--", "/*", "*/"}:
233
+ raise MostlyDataException("Empty SQL statement.")
234
+
235
+ statements = sqlparse.parse(sql)
236
+ if not statements:
237
+ raise MostlyDataException("Empty SQL statement.")
238
+
239
+ for statement in statements:
240
+ # check if statement contains only comments or whitespace
241
+ tokens = [t for t in statement.tokens if not t.is_whitespace]
242
+ if not tokens or all(
243
+ t.ttype in (sqlparse.tokens.Comment.Single, sqlparse.tokens.Comment.Multiline) for t in tokens
244
+ ):
245
+ raise MostlyDataException("Empty SQL statement.")
246
+
247
+ # get the first token to check for disallowed operations
248
+ first_token = statement.token_first()
249
+ if first_token and first_token.value.lower() in disallowed_operations:
250
+ raise MostlyDataException(f"Disallowed operation: {first_token.value.upper()}")
251
+
252
+ # check for DML operations
253
+ for token in statement.flatten():
254
+ if token.ttype is DML:
255
+ dml = token.value.lower()
256
+ if dml not in read_only_dml:
257
+ raise MostlyDataException(f"Disallowed operation: {dml.upper()}")
258
+
259
+ # check for disallowed keywords in proper SQL context
260
+ tokens = [t for t in statement.flatten() if t.ttype is not None]
261
+ in_case = False # track if we're inside a CASE expression
262
+ for i, token in enumerate(tokens):
263
+ if token.value.lower() == "case":
264
+ in_case = True
265
+ elif token.value.lower() == "end" and in_case:
266
+ in_case = False
267
+ continue # skip END if it's part of a CASE expression
268
+ elif token.value.lower() in disallowed_operations:
269
+ # check if it's a standalone keyword or part of a larger token
270
+ if i > 0 and tokens[i - 1].value.lower() in {"from", "into", "to", "on", "where", "and", "or", "not"}:
271
+ continue # skip if it's part of a larger expression
272
+ raise MostlyDataException(f"Disallowed operation: {token.value.upper()}")
273
+
274
+
180
275
  MAX_SCP_SIBLINGS_LIMIT = 50
181
276
  TABLE_COLUMN_INFIX = "::"
182
277
  NON_CONTEXT_COLUMN_INFIX = "."
@@ -106,3 +106,14 @@ def delete_data_from_connector(connector: Connector, config: ConnectorDeleteData
106
106
  data_table.drop()
107
107
  except Exception as e:
108
108
  raise HTTPException(status_code=400, detail=str(e))
109
+
110
+
111
+ def query_data_from_connector(connector: Connector, sql: str) -> pd.DataFrame:
112
+ if connector.access_type not in {ConnectorAccessType.read_data, ConnectorAccessType.write_data}:
113
+ raise HTTPException(status_code=400, detail="Connector does not have query access")
114
+
115
+ try:
116
+ data_container = create_container_from_connector(connector)
117
+ return data_container.query(sql)
118
+ except Exception as e:
119
+ raise HTTPException(status_code=400, detail=str(e))
@@ -235,8 +235,9 @@ class Routes:
235
235
  df = connectors.read_data_from_connector(connector, config)
236
236
 
237
237
  # this file can only be safely removed once the streaming response is complete
238
- tmp_path = tempfile.mktemp(suffix=".parquet")
239
- df.to_parquet(tmp_path)
238
+ with tempfile.NamedTemporaryFile(suffix=".parquet", delete=False) as tmp_file:
239
+ tmp_path = tmp_file.name
240
+ df.to_parquet(tmp_path)
240
241
 
241
242
  return StreamingResponse(
242
243
  open(tmp_path, mode="rb"),
@@ -264,6 +265,24 @@ class Routes:
264
265
  connector = read_connector_from_json(connector_dir)
265
266
  connectors.delete_data_from_connector(connector, config)
266
267
 
268
+ @self.router.post("/connectors/{id}/query")
269
+ async def query(id: str, sql: str = Body(..., embed=True)) -> StreamingResponse:
270
+ connector_dir = self.home_dir / "connectors" / id
271
+ connector = read_connector_from_json(connector_dir)
272
+ df = connectors.query_data_from_connector(connector, sql)
273
+
274
+ # this file can only be safely removed once the streaming response is complete
275
+ with tempfile.NamedTemporaryFile(suffix=".parquet", delete=False) as tmp_file:
276
+ tmp_path = tmp_file.name
277
+ df.to_parquet(tmp_path)
278
+
279
+ return StreamingResponse(
280
+ open(tmp_path, mode="rb"),
281
+ media_type="application/octet-stream",
282
+ headers={"Content-Disposition": "attachment; filename=query_result.parquet"},
283
+ background=BackgroundTask(Path(tmp_path).unlink, missing_ok=True),
284
+ )
285
+
267
286
  ## GENERATORS
268
287
 
269
288
  @self.router.get("/generators")
@@ -222,3 +222,18 @@ class _MostlyConnectorsClient(_MostlyBaseClient):
222
222
  path=[connector_id, "delete-data"],
223
223
  json=config_data,
224
224
  )
225
+
226
+ def _query(self, connector_id: str, sql: str) -> pd.DataFrame:
227
+ response = self.request(
228
+ verb=POST,
229
+ path=[connector_id, "query"],
230
+ json={"sql": sql},
231
+ headers={
232
+ "Content-Type": "application/json",
233
+ "Accept": "application/octet-stream, application/json",
234
+ },
235
+ raw_response=True,
236
+ )
237
+ content_bytes = response.content
238
+ df = pd.read_parquet(io.BytesIO(content_bytes))
239
+ return df
@@ -13,7 +13,7 @@
13
13
  # limitations under the License.
14
14
 
15
15
  # generated by datamodel-codegen:
16
- # timestamp: 2025-03-27T23:05:51+00:00
16
+ # timestamp: 2025-04-01T14:13:05+00:00
17
17
 
18
18
  from __future__ import annotations
19
19
 
@@ -442,7 +442,10 @@ class ConnectorWriteDataConfig(CustomBaseModel):
442
442
  Configuration for writing data to a connector.
443
443
  """
444
444
 
445
- file: bytes = Field(..., description="Binary Parquet file containing the data to write.")
445
+ file: bytes = Field(
446
+ ...,
447
+ description="Binary Parquet file containing the data to write. If null, a delete data operation occurs.",
448
+ )
446
449
  location: str = Field(
447
450
  ...,
448
451
  description="Specifies the target within the connector to which to write the data. The format of this parameter varies by connector type.",
@@ -454,6 +457,10 @@ class ConnectorWriteDataConfig(CustomBaseModel):
454
457
  )
455
458
 
456
459
 
460
+ class ConnectorQueryConfig(CustomBaseModel):
461
+ sql: str = Field(..., description="SQL read-only (e.g. SELECT) statement to execute.")
462
+
463
+
457
464
  class GeneratorUsage(CustomBaseModel):
458
465
  """
459
466
  Usage statistics of a generator.
@@ -1874,6 +1881,22 @@ class Connector(CustomBaseModel):
1874
1881
  """
1875
1882
  self.client._delete_data(connector_id=self.id, location=location)
1876
1883
 
1884
+ def query(self, sql: str) -> pd.DataFrame:
1885
+ """
1886
+ Execute a read-only SQL query against the connector's data source.
1887
+
1888
+ Queries can include statements like SELECT, SHOW, or DESCRIBE, but must not modify data or state.
1889
+ For file-based connectors (e.g., local files or cloud storage buckets like AWS S3, GCP, Azure Blob),
1890
+ queries are executed using DuckDB.
1891
+
1892
+ Args:
1893
+ sql (str): The SQL query to execute.
1894
+
1895
+ Returns:
1896
+ pd.DataFrame: The result of the query as a Pandas DataFrame.
1897
+ """
1898
+ return self.client._query(connector_id=self.id, sql=sql)
1899
+
1877
1900
 
1878
1901
  class GeneratorListItem(CustomBaseModel):
1879
1902
  """
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "mostlyai"
3
- version = "4.4.5"
3
+ version = "4.4.6"
4
4
  description = "Synthetic Data SDK"
5
5
  authors = [{ name = "MOSTLY AI", email = "dev@mostly.ai" }]
6
6
  requires-python = ">=3.10,<3.14"
@@ -41,13 +41,15 @@ dependencies = [
41
41
  "greenlet>=3.1.1,<4",
42
42
  "pycryptodomex>=3.10.0,<4",
43
43
  "ipywidgets>=8.1.0",
44
+ "duckdb>=1.2.1",
45
+ "sqlparse>=0.5.3",
44
46
  ]
45
47
 
46
48
  [project.optional-dependencies]
47
49
  local = [
48
50
  # local
49
- "mostlyai-engine==1.1.10",
50
- "mostlyai-qa==1.5.11",
51
+ "mostlyai-engine==1.1.11",
52
+ "mostlyai-qa==1.5.12",
51
53
  "fastapi>=0.115.6,<0.116",
52
54
  "uvicorn>=0.34.0,<0.35",
53
55
  "python-multipart>=0.0.20",
@@ -71,8 +73,8 @@ local = [
71
73
  "adlfs>=2023.4.0",
72
74
  ]
73
75
  local-gpu = [
74
- "mostlyai-engine[gpu]==1.1.10",
75
- "mostlyai-qa[gpu]==1.5.11",
76
+ "mostlyai-engine[gpu]==1.1.11",
77
+ "mostlyai-qa[gpu]==1.5.12",
76
78
  "fastapi>=0.115.6,<0.116",
77
79
  "uvicorn>=0.34.0,<0.35",
78
80
  "python-multipart>=0.0.20",
@@ -96,8 +98,8 @@ local-gpu = [
96
98
  "adlfs>=2023.4.0",
97
99
  ]
98
100
  local-cpu = [
99
- "mostlyai-engine[cpu]==1.1.10",
100
- "mostlyai-qa[cpu]==1.5.11",
101
+ "mostlyai-engine[cpu]==1.1.11",
102
+ "mostlyai-qa[cpu]==1.5.12",
101
103
  "fastapi>=0.115.6,<0.116",
102
104
  "uvicorn>=0.34.0,<0.35",
103
105
  "python-multipart>=0.0.20",
File without changes
File without changes
File without changes
File without changes