mostlyai 5.2.6__tar.gz → 5.3.0__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 (90) hide show
  1. {mostlyai-5.2.6 → mostlyai-5.3.0}/PKG-INFO +6 -4
  2. {mostlyai-5.2.6 → mostlyai-5.3.0}/README.md +1 -1
  3. mostlyai-5.3.0/mostlyai/sdk/__init__.py +52 -0
  4. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/conversions.py +2 -0
  5. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/db/base.py +4 -4
  6. mostlyai-5.3.0/mostlyai/sdk/_data/db/redshift.py +433 -0
  7. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/dtype.py +2 -2
  8. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/non_context.py +1 -1
  9. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/pull_utils.py +3 -3
  10. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/domain.py +153 -134
  11. {mostlyai-5.2.6 → mostlyai-5.3.0}/pyproject.toml +6 -3
  12. mostlyai-5.2.6/mostlyai/sdk/__init__.py +0 -18
  13. {mostlyai-5.2.6 → mostlyai-5.3.0}/.gitignore +0 -0
  14. {mostlyai-5.2.6 → mostlyai-5.3.0}/LICENSE +0 -0
  15. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/__init__.py +0 -0
  16. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/auto_detect.py +0 -0
  17. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/base.py +0 -0
  18. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/context.py +0 -0
  19. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/db/__init__.py +0 -0
  20. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/db/bigquery.py +0 -0
  21. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/db/databricks.py +0 -0
  22. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/db/hive.py +0 -0
  23. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/db/mssql.py +0 -0
  24. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/db/mysql.py +0 -0
  25. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/db/oracle.py +0 -0
  26. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/db/postgresql.py +0 -0
  27. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/db/snowflake.py +0 -0
  28. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/db/sqlite.py +0 -0
  29. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/db/types_coercion.py +0 -0
  30. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/exceptions.py +0 -0
  31. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/file/__init__.py +0 -0
  32. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/file/base.py +0 -0
  33. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/file/container/__init__.py +0 -0
  34. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/file/container/aws.py +0 -0
  35. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/file/container/azure.py +0 -0
  36. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/file/container/bucket_based.py +0 -0
  37. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/file/container/gcs.py +0 -0
  38. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/file/container/minio.py +0 -0
  39. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/file/table/__init__.py +0 -0
  40. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/file/table/csv.py +0 -0
  41. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/file/table/feather.py +0 -0
  42. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/file/table/json.py +0 -0
  43. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/file/table/parquet.py +0 -0
  44. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/file/utils.py +0 -0
  45. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/language_model.py +0 -0
  46. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/metadata_objects.py +0 -0
  47. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/progress_callback.py +0 -0
  48. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/pull.py +0 -0
  49. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/pull_context.py +0 -0
  50. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/push.py +0 -0
  51. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/util/__init__.py +0 -0
  52. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/util/common.py +0 -0
  53. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_data/util/kerberos.py +0 -0
  54. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/__init__.py +0 -0
  55. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/cli.py +0 -0
  56. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/connectors.py +0 -0
  57. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/execution/__init__.py +0 -0
  58. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/execution/jobs.py +0 -0
  59. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/execution/migration.py +0 -0
  60. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/execution/plan.py +0 -0
  61. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/execution/step_analyze_training_data.py +0 -0
  62. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/execution/step_create_data_report.py +0 -0
  63. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/execution/step_create_model_report.py +0 -0
  64. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/execution/step_deliver_data.py +0 -0
  65. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/execution/step_encode_training_data.py +0 -0
  66. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/execution/step_finalize_generation.py +0 -0
  67. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/execution/step_finalize_training.py +0 -0
  68. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/execution/step_generate_data.py +0 -0
  69. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/execution/step_generate_model_report_data.py +0 -0
  70. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/execution/step_pull_training_data.py +0 -0
  71. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/execution/step_train_model.py +0 -0
  72. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/generators.py +0 -0
  73. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/progress.py +0 -0
  74. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/routes.py +0 -0
  75. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/server.py +0 -0
  76. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/storage.py +0 -0
  77. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/_local/synthetic_datasets.py +0 -0
  78. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/client/__init__.py +0 -0
  79. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/client/_base_utils.py +0 -0
  80. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/client/_naming_conventions.py +0 -0
  81. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/client/_utils.py +0 -0
  82. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/client/api.py +0 -0
  83. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/client/artifacts.py +0 -0
  84. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/client/base.py +0 -0
  85. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/client/connectors.py +0 -0
  86. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/client/datasets.py +0 -0
  87. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/client/exceptions.py +0 -0
  88. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/client/generators.py +0 -0
  89. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/client/synthetic_datasets.py +0 -0
  90. {mostlyai-5.2.6 → mostlyai-5.3.0}/mostlyai/sdk/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mostlyai
3
- Version: 5.2.6
3
+ Version: 5.3.0
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
@@ -59,7 +59,7 @@ Requires-Dist: fastapi<0.116,>=0.115.6; extra == 'local'
59
59
  Requires-Dist: filelock>=3.16.1; extra == 'local'
60
60
  Requires-Dist: gcsfs>=2023.1.0; extra == 'local'
61
61
  Requires-Dist: joblib>=1.4.2; extra == 'local'
62
- Requires-Dist: mostlyai-engine==1.5.7; extra == 'local'
62
+ Requires-Dist: mostlyai-engine==1.5.8; extra == 'local'
63
63
  Requires-Dist: mostlyai-qa==1.9.8; extra == 'local'
64
64
  Requires-Dist: networkx<4,>=3.0; extra == 'local'
65
65
  Requires-Dist: openpyxl>=3.1.5; extra == 'local'
@@ -81,7 +81,7 @@ Requires-Dist: fastapi<0.116,>=0.115.6; extra == 'local-gpu'
81
81
  Requires-Dist: filelock>=3.16.1; extra == 'local-gpu'
82
82
  Requires-Dist: gcsfs>=2023.1.0; extra == 'local-gpu'
83
83
  Requires-Dist: joblib>=1.4.2; extra == 'local-gpu'
84
- Requires-Dist: mostlyai-engine[gpu]==1.5.7; extra == 'local-gpu'
84
+ Requires-Dist: mostlyai-engine[gpu]==1.5.8; extra == 'local-gpu'
85
85
  Requires-Dist: mostlyai-qa==1.9.8; extra == 'local-gpu'
86
86
  Requires-Dist: networkx<4,>=3.0; extra == 'local-gpu'
87
87
  Requires-Dist: openpyxl>=3.1.5; extra == 'local-gpu'
@@ -103,6 +103,8 @@ Provides-Extra: oracle
103
103
  Requires-Dist: oracledb<3,>=2.2.1; extra == 'oracle'
104
104
  Provides-Extra: postgres
105
105
  Requires-Dist: psycopg2<3,>=2.9.4; extra == 'postgres'
106
+ Provides-Extra: redshift
107
+ Requires-Dist: redshift-connector>=2.1.8; extra == 'redshift'
106
108
  Provides-Extra: snowflake
107
109
  Requires-Dist: snowflake-sqlalchemy<2,>=1.6.1; extra == 'snowflake'
108
110
  Description-Content-Type: text/markdown
@@ -339,7 +341,7 @@ pip install -U torch==2.7.0+cpu torchvision==0.22.0+cpu 'mostlyai[local]' --extr
339
341
 
340
342
  ### Data Connectors
341
343
 
342
- Add any of the following extras for further data connectors support in LOCAL mode: `databricks`, `googlebigquery`, `hive`, `mssql`, `mysql`, `oracle`, `postgres`, `snowflake`. E.g.
344
+ Add any of the following extras for further data connectors support in LOCAL mode: `databricks`, `googlebigquery`, `hive`, `mssql`, `mysql`, `oracle`, `postgres`, `redshift`, `snowflake`. E.g.
343
345
 
344
346
  ```shell
345
347
  uv pip install -U 'mostlyai[local, databricks, snowflake]'
@@ -230,7 +230,7 @@ pip install -U torch==2.7.0+cpu torchvision==0.22.0+cpu 'mostlyai[local]' --extr
230
230
 
231
231
  ### Data Connectors
232
232
 
233
- Add any of the following extras for further data connectors support in LOCAL mode: `databricks`, `googlebigquery`, `hive`, `mssql`, `mysql`, `oracle`, `postgres`, `snowflake`. E.g.
233
+ Add any of the following extras for further data connectors support in LOCAL mode: `databricks`, `googlebigquery`, `hive`, `mssql`, `mysql`, `oracle`, `postgres`, `redshift`, `snowflake`. E.g.
234
234
 
235
235
  ```shell
236
236
  uv pip install -U 'mostlyai[local, databricks, snowflake]'
@@ -0,0 +1,52 @@
1
+ # Copyright 2024-2025 MOSTLY AI
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Synthetic Data SDK - Python toolkit for high-fidelity, privacy-safe synthetic data.
16
+
17
+ The SDK supports two operating modes:
18
+ - LOCAL mode: Train and generate synthetic data locally on your own compute resources
19
+ - CLIENT mode: Connect to a remote MOSTLY AI platform for training & generation
20
+
21
+ Key Resources
22
+ -------------
23
+ The SDK manages four core resources:
24
+
25
+ 1. **Generators** - Train synthetic data generators on tabular or language data
26
+ 2. **Synthetic Datasets** - Create synthetic samples from trained generators
27
+ 3. **Connectors** - Connect to data sources (databases, cloud storage)
28
+ 4. **Datasets** - Create datasets with instructions (CLIENT mode only)
29
+
30
+ Core Operations
31
+ ---------------
32
+ - `mostly.train(config)` - Train a generator on tabular or language data
33
+ - `mostly.generate(g, config)` - Generate synthetic data records
34
+ - `mostly.probe(g, config)` - Live probe the generator on demand
35
+ - `mostly.connect(config)` - Connect to external data sources
36
+
37
+ Key Features
38
+ ------------
39
+ - Broad data support (mixed-type, single/multi-table, time-series)
40
+ - Multiple model types (TabularARGN, Hugging Face LLMs, LSTM)
41
+ - Advanced training options (GPU/CPU, Differential Privacy)
42
+ - Automated quality assurance with metrics and HTML reports
43
+ - Flexible sampling (up-sampling, conditional simulation, rebalancing)
44
+ - Seamless integration with external data sources
45
+
46
+ For more information, visit: https://mostly-ai.github.io/mostlyai/
47
+ """
48
+
49
+ from mostlyai.sdk.client.api import MostlyAI
50
+
51
+ __all__ = ["MostlyAI"]
52
+ __version__ = "5.3.0" # Do not set this manually. Use poetry version [params].
@@ -26,6 +26,7 @@ _LOG = logging.getLogger(__name__)
26
26
  CONNECTOR_TYPE_CONTAINER_CLASS_MAP = {
27
27
  ConnectorType.mysql: "mostlyai.sdk._data.db.mysql.MysqlContainer",
28
28
  ConnectorType.postgres: "mostlyai.sdk._data.db.postgresql.PostgresqlContainer",
29
+ ConnectorType.redshift: "mostlyai.sdk._data.db.redshift.RedshiftContainer",
29
30
  ConnectorType.mssql: "mostlyai.sdk._data.db.mssql.MssqlContainer",
30
31
  ConnectorType.oracle: "mostlyai.sdk._data.db.oracle.OracleContainer",
31
32
  ConnectorType.mariadb: "mostlyai.sdk._data.db.mysql.MariadbContainer",
@@ -43,6 +44,7 @@ CONNECTOR_TYPE_CONTAINER_CLASS_MAP = {
43
44
  CONNECTOR_TYPE_CONTAINER_PARAMS_CLASS_MAP = {
44
45
  ConnectorType.mysql: "mostlyai.sdk._data.metadata_objects.SqlAlchemyContainerParameters",
45
46
  ConnectorType.postgres: "mostlyai.sdk._data.metadata_objects.SqlAlchemyContainerParameters",
47
+ ConnectorType.redshift: "mostlyai.sdk._data.metadata_objects.SqlAlchemyContainerParameters",
46
48
  ConnectorType.mssql: "mostlyai.sdk._data.metadata_objects.SqlAlchemyContainerParameters",
47
49
  ConnectorType.oracle: "mostlyai.sdk._data.metadata_objects.OracleContainerParameters",
48
50
  ConnectorType.mariadb: "mostlyai.sdk._data.metadata_objects.SqlAlchemyContainerParameters",
@@ -862,7 +862,7 @@ def use_ssh_tunnel(
862
862
  class SqlAlchemyTable(DBTable, abc.ABC):
863
863
  ENABLE_ORDER_AND_LIMIT_ON_SQL: bool = True
864
864
  IS_SERVER_SIDE_CURSOR_AVAILABLE: bool = True
865
- SA_RANDOM: sa.sql.Executable | None = None # must be overriden
865
+ SA_RANDOM: sa.sql.Executable | None = None # must be overridden
866
866
  SA_MAX_VALS_PER_BATCH: int = 10_000
867
867
  SA_MAX_VALS_PER_IN_CLAUSE: int | None = None
868
868
  SA_CONN_DIALECT_PROPS: dict[str, Any] | None = None
@@ -1129,11 +1129,11 @@ class SqlAlchemyTable(DBTable, abc.ABC):
1129
1129
  chunk_idx = 0
1130
1130
  total_time = 0
1131
1131
  session = sessionmaker(bind=sa_engine)()
1132
- result = session.execute(stmt, execution_options={"stream_results": True}).yield_per(fetch_chunk_size)
1132
+ conn = session.connection()
1133
+ results_generator = pd.read_sql_query(stmt, conn, dtype_backend="pyarrow", chunksize=fetch_chunk_size)
1133
1134
  chunks_df = pd.DataFrame()
1134
- while sa_rows := result.fetchmany(fetch_chunk_size):
1135
+ for chunk_df in results_generator:
1135
1136
  t0 = time.time()
1136
- chunk_df = pd.DataFrame(sa_rows).convert_dtypes(dtype_backend="pyarrow")
1137
1137
  if where is not None:
1138
1138
  where_column, where_values = next(iter(where.items()))
1139
1139
  chunk_df = chunk_df[chunk_df[where_column].isin(where_values)]
@@ -0,0 +1,433 @@
1
+ # Copyright 2025 MOSTLY AI
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import logging
16
+ import warnings
17
+ from urllib.parse import quote
18
+
19
+ import pandas as pd
20
+ import redshift_connector
21
+ import sqlalchemy as sa
22
+ from sqlalchemy import text, types
23
+ from sqlalchemy.dialects import registry
24
+ from sqlalchemy.engine.default import DefaultDialect
25
+
26
+ from mostlyai.sdk._data.db.base import DBDType
27
+ from mostlyai.sdk._data.db.postgresql import PostgresqlContainer, PostgresqlTable
28
+
29
+ # suppress ssl deprecation warnings from redshift_connector
30
+ warnings.filterwarnings(
31
+ "ignore", message="ssl.SSLContext.*without protocol argument is deprecated", category=DeprecationWarning
32
+ )
33
+ warnings.filterwarnings("ignore", message="ssl.PROTOCOL_TLS is deprecated", category=DeprecationWarning)
34
+
35
+ _LOG = logging.getLogger(__name__)
36
+
37
+
38
+ # minimal DBAPI wrapper for redshift_connector
39
+ class RedshiftDBAPI:
40
+ paramstyle = "format" # redshift_connector uses format style (%s)
41
+ apilevel = "2.0"
42
+ threadsafety = 1
43
+
44
+ @staticmethod
45
+ def connect(*args, **kwargs):
46
+ # map sqlalchemy parameter names to redshift-connector parameter names
47
+ param_mapping = {"username": "user", "dbname": "database"}
48
+ redshift_kwargs = {param_mapping.get(key, key): value for key, value in kwargs.items()}
49
+ return redshift_connector.connect(**redshift_kwargs)
50
+
51
+ Error = redshift_connector.Error
52
+ InterfaceError = redshift_connector.InterfaceError
53
+ DatabaseError = redshift_connector.DatabaseError
54
+ DataError = redshift_connector.DataError
55
+ OperationalError = redshift_connector.OperationalError
56
+ IntegrityError = redshift_connector.IntegrityError
57
+ InternalError = redshift_connector.InternalError
58
+ ProgrammingError = redshift_connector.ProgrammingError
59
+ NotSupportedError = redshift_connector.NotSupportedError
60
+
61
+
62
+ # minimal redshift dialect that inherits from DefaultDialect instead of PGDialect
63
+ class RedshiftDialect(DefaultDialect):
64
+ name = "redshift"
65
+ driver = "redshift_connector"
66
+ supports_statement_cache = False
67
+ default_paramstyle = "format"
68
+
69
+ # redshift-specific capabilities
70
+ supports_alter = True
71
+ supports_unicode_statements = True
72
+ supports_unicode_binds = True
73
+ supports_native_boolean = True
74
+ supports_native_decimal = True
75
+ supports_schemas = True
76
+ supports_sequences = False # redshift doesn't support sequences
77
+ supports_identity_columns = False # redshift doesn't support identity columns
78
+ supports_comments = True
79
+ supports_default_values = True
80
+ supports_empty_inserts = False
81
+ supports_multivalues_insert = True
82
+
83
+ def __init__(self, **kwargs):
84
+ super().__init__(**kwargs)
85
+ self.on_connect = lambda: None
86
+
87
+ @classmethod
88
+ def import_dbapi(cls):
89
+ return RedshiftDBAPI
90
+
91
+ def _execute_information_schema_query(self, connection, query, params):
92
+ """helper method to execute information_schema queries with common error handling"""
93
+ return connection.execute(text(query), params)
94
+
95
+ def _get_schema_or_default(self, schema):
96
+ """helper method to get schema name with default fallback"""
97
+ return schema or "public"
98
+
99
+ def _query_table_names_by_type(self, connection, schema, table_type):
100
+ """helper method to query table names by type (BASE TABLE or VIEW)"""
101
+ schema = self._get_schema_or_default(schema)
102
+
103
+ query = """
104
+ SELECT table_name
105
+ FROM information_schema.tables
106
+ WHERE table_schema = :schema AND table_type = :table_type
107
+ ORDER BY table_name
108
+ """
109
+
110
+ result = self._execute_information_schema_query(connection, query, {"schema": schema, "table_type": table_type})
111
+ return [row[0] for row in result.fetchall()]
112
+
113
+ def get_table_names(self, connection, schema=None, **kw):
114
+ """get table names using information_schema for redshift compatibility"""
115
+ return self._query_table_names_by_type(connection, schema, "BASE TABLE")
116
+
117
+ def get_view_names(self, connection, schema=None, **kw):
118
+ """get view names using information_schema for redshift compatibility"""
119
+ return self._query_table_names_by_type(connection, schema, "VIEW")
120
+
121
+ def get_columns(self, connection, table_name, schema=None, **kw):
122
+ """get column information using information_schema for redshift compatibility"""
123
+ schema = self._get_schema_or_default(schema)
124
+
125
+ query = """
126
+ SELECT
127
+ column_name,
128
+ data_type,
129
+ is_nullable,
130
+ column_default,
131
+ character_maximum_length,
132
+ numeric_precision,
133
+ numeric_scale
134
+ FROM information_schema.columns
135
+ WHERE table_schema = :schema AND table_name = :table_name
136
+ ORDER BY ordinal_position
137
+ """
138
+
139
+ result = self._execute_information_schema_query(connection, query, {"schema": schema, "table_name": table_name})
140
+
141
+ columns = []
142
+ for row in result.fetchall():
143
+ columns.append(
144
+ {
145
+ "name": row[0],
146
+ "type": self._get_column_type(row[1], row[4], row[5], row[6]),
147
+ "nullable": row[2] == "YES",
148
+ "default": row[3],
149
+ }
150
+ )
151
+ return columns
152
+
153
+ def _get_column_type(self, data_type, max_length, precision, scale):
154
+ """map redshift data types to sqlalchemy types"""
155
+ type_map = {
156
+ "character varying": lambda: types.VARCHAR(max_length) if max_length else types.VARCHAR(),
157
+ "character": lambda: types.CHAR(max_length) if max_length else types.CHAR(),
158
+ "varchar": lambda: types.VARCHAR(max_length) if max_length else types.VARCHAR(),
159
+ "char": lambda: types.CHAR(max_length) if max_length else types.CHAR(),
160
+ "text": lambda: types.TEXT(),
161
+ "integer": lambda: types.INTEGER(),
162
+ "bigint": lambda: types.BIGINT(),
163
+ "smallint": lambda: types.SMALLINT(),
164
+ "decimal": lambda: types.DECIMAL(precision, scale) if precision else types.DECIMAL(),
165
+ "numeric": lambda: types.NUMERIC(precision, scale) if precision else types.NUMERIC(),
166
+ "real": lambda: types.REAL(),
167
+ "double precision": lambda: types.FLOAT(),
168
+ "boolean": lambda: types.BOOLEAN(),
169
+ "date": lambda: types.DATE(),
170
+ "timestamp": lambda: types.TIMESTAMP(),
171
+ "timestamp without time zone": lambda: types.TIMESTAMP(),
172
+ "timestamp with time zone": lambda: types.TIMESTAMP(timezone=True),
173
+ "time": lambda: types.TIME(),
174
+ "time without time zone": lambda: types.TIME(),
175
+ "time with time zone": lambda: types.TIME(timezone=True),
176
+ # redshift-specific types
177
+ "super": lambda: types.JSON(), # super type for semi-structured data, map to JSON
178
+ "geometry": lambda: types.TEXT(), # geometry type, map to text for sqlalchemy
179
+ "geography": lambda: types.TEXT(), # geography type, map to text for sqlalchemy
180
+ "hllsketch": lambda: types.TEXT(), # hllsketch type, map to text for sqlalchemy
181
+ "varbyte": lambda: types.BINARY(), # varbyte type, map to binary
182
+ }
183
+
184
+ return type_map.get(data_type.lower(), lambda: types.NULLTYPE)()
185
+
186
+ def get_pk_constraint(self, connection, table_name, schema=None, **kw):
187
+ """get primary key constraint information (non-enforced in redshift)"""
188
+ schema = self._get_schema_or_default(schema)
189
+
190
+ query = """
191
+ SELECT
192
+ t.constraint_name,
193
+ c.column_name
194
+ FROM
195
+ information_schema.table_constraints t
196
+ JOIN
197
+ information_schema.key_column_usage c
198
+ ON t.constraint_name = c.constraint_name
199
+ AND t.table_schema = c.table_schema
200
+ AND t.table_name = c.table_name
201
+ WHERE
202
+ t.table_schema = :schema
203
+ AND t.table_name = :table_name
204
+ AND t.constraint_type = 'PRIMARY KEY'
205
+ ORDER BY
206
+ c.ordinal_position
207
+ """
208
+
209
+ result = self._execute_information_schema_query(connection, query, {"schema": schema, "table_name": table_name})
210
+
211
+ columns = []
212
+ constraint_name = None
213
+ for row in result.fetchall():
214
+ if constraint_name is None:
215
+ constraint_name = row[0]
216
+ columns.append(row[1])
217
+
218
+ return {"constrained_columns": columns, "name": constraint_name}
219
+
220
+ def get_foreign_keys(self, connection, table_name, schema=None, **kw):
221
+ """get foreign key constraint information (non-enforced in redshift)"""
222
+ schema = self._get_schema_or_default(schema)
223
+
224
+ query = """
225
+ SELECT
226
+ tc.constraint_name,
227
+ kcu.column_name,
228
+ ccu.table_schema AS foreign_table_schema,
229
+ ccu.table_name AS foreign_table_name,
230
+ ccu.column_name AS foreign_column_name
231
+ FROM
232
+ information_schema.table_constraints AS tc
233
+ JOIN information_schema.key_column_usage AS kcu
234
+ ON tc.constraint_name = kcu.constraint_name
235
+ AND tc.table_schema = kcu.table_schema
236
+ JOIN information_schema.constraint_column_usage AS ccu
237
+ ON ccu.constraint_name = tc.constraint_name
238
+ AND ccu.table_schema = tc.table_schema
239
+ WHERE
240
+ tc.constraint_type = 'FOREIGN KEY'
241
+ AND tc.table_schema = :schema
242
+ AND tc.table_name = :table_name
243
+ ORDER BY
244
+ tc.constraint_name,
245
+ kcu.ordinal_position
246
+ """
247
+
248
+ result = self._execute_information_schema_query(connection, query, {"schema": schema, "table_name": table_name})
249
+
250
+ # group by constraint name
251
+ fkeys = {}
252
+ for row in result:
253
+ const_name, col_name, ref_schema, ref_table, ref_col = row
254
+ if const_name not in fkeys:
255
+ fkeys[const_name] = {
256
+ "name": const_name,
257
+ "constrained_columns": [],
258
+ "referred_schema": ref_schema,
259
+ "referred_table": ref_table,
260
+ "referred_columns": [],
261
+ }
262
+ fkeys[const_name]["constrained_columns"].append(col_name)
263
+ fkeys[const_name]["referred_columns"].append(ref_col)
264
+
265
+ return list(fkeys.values())
266
+
267
+ def get_indexes(self, connection, table_name, schema=None, **kw):
268
+ """get index information"""
269
+ # redshift doesn't support traditional indexes, return empty
270
+ return []
271
+
272
+ def get_unique_constraints(self, connection, table_name, schema=None, **kw):
273
+ """get unique constraint information"""
274
+ # redshift doesn't enforce unique constraints, return empty
275
+ return []
276
+
277
+ def has_table(self, connection, table_name, schema=None, **kw):
278
+ """check if table exists - case-insensitive for redshift"""
279
+ schema = self._get_schema_or_default(schema)
280
+ query = """
281
+ SELECT COUNT(*)
282
+ FROM information_schema.tables
283
+ WHERE table_schema = :schema AND LOWER(table_name) = LOWER(:table_name)
284
+ """
285
+ result = self._execute_information_schema_query(connection, query, {"schema": schema, "table_name": table_name})
286
+ return result.scalar() > 0
287
+
288
+ def get_schema_names(self, connection, **kw):
289
+ """get all schema names using pg_namespace system catalog"""
290
+ query = """
291
+ SELECT nspname
292
+ FROM pg_namespace
293
+ WHERE nspname NOT LIKE 'pg_%'
294
+ AND nspname != 'information_schema'
295
+ ORDER BY nspname
296
+ """
297
+
298
+ result = connection.execute(text(query))
299
+ return [row[0] for row in result.fetchall()]
300
+
301
+
302
+ def _ensure_dialect_registered():
303
+ """ensure the redshift dialect is registered with sqlalchemy"""
304
+ registry.register("redshift.redshift_connector", __name__, "RedshiftDialect")
305
+
306
+
307
+ def _init_worker():
308
+ """initialize worker process: suppress case warnings"""
309
+ warnings.filterwarnings("ignore", message=".*not found exactly.*case sensitivity.*")
310
+
311
+
312
+ # register the dialect immediately when module is imported
313
+ _ensure_dialect_registered()
314
+
315
+
316
+ class RedshiftDType(DBDType):
317
+ FROM_VIRTUAL_DATETIME = sa.TIMESTAMP
318
+
319
+ @classmethod
320
+ def sa_dialect_class(cls):
321
+ return RedshiftDialect
322
+
323
+
324
+ class RedshiftContainer(PostgresqlContainer):
325
+ SCHEMES = ["redshift"]
326
+ # redshift-connector enables ssl by default; don't pass postgres-specific ssl args
327
+ SA_CONNECTION_KWARGS = {}
328
+ SA_SSL_ATTR_KEY_MAP = {}
329
+ # redshift-connector doesn't support connect_timeout parameter
330
+ SA_CONNECT_ARGS_ACCESS_ENGINE = {}
331
+ INIT_DEFAULT_VALUES = {"dbname": "", "port": "5439"}
332
+
333
+ def __init__(self, *args, **kwargs):
334
+ super().__init__(*args, **kwargs)
335
+
336
+ @property
337
+ def sa_uri(self):
338
+ # encode credentials and database name to handle special characters
339
+ username = quote(self.username, safe="")
340
+ password = quote(self.password, safe="")
341
+ dbname = quote(self.dbname, safe="")
342
+ # use redshift+redshift_connector dialect
343
+ return f"redshift+redshift_connector://{username}:{password}@{self.host}:{self.port}/{dbname}"
344
+
345
+ @property
346
+ def sa_create_engine_kwargs(self) -> dict:
347
+ # redshift-connector doesn't support executemany_* parameters
348
+ # use only standard sqlalchemy engine parameters
349
+ return {
350
+ # optimize connection pooling for redshift
351
+ # pool_size: base connections kept alive (aligned with typical workload)
352
+ "pool_size": 2,
353
+ # max_overflow: additional connections allowed (matches WRITE_CHUNKS_N_JOBS parallelism)
354
+ "max_overflow": 2,
355
+ # pool_timeout: seconds to wait for available connection
356
+ "pool_timeout": 30,
357
+ # pool_recycle: recycle connections after 1 hour to avoid stale connections
358
+ "pool_recycle": 3600,
359
+ }
360
+
361
+ @classmethod
362
+ def table_class(cls):
363
+ return RedshiftTable
364
+
365
+
366
+ class RedshiftTable(PostgresqlTable):
367
+ DATA_TABLE_TYPE = "redshift"
368
+ SA_RANDOM = sa.func.rand()
369
+ WRITE_CHUNK_SIZE = 3_000 # redshift bind parameter limit: 32767 params
370
+ SA_MULTIPLE_INSERTS = True
371
+ WRITE_CHUNKS_N_JOBS = 2
372
+
373
+ @property
374
+ def _sa_table(self):
375
+ # override to ensure schema is explicitly passed and handle case-insensitive table names
376
+ with self.container.use_sa_engine() as sa_engine:
377
+ schema = self.container.dbschema or "public"
378
+ inspector = sa.inspect(sa_engine)
379
+ available_tables = inspector.get_table_names(schema=schema)
380
+
381
+ # redshift dialect's has_table is case-insensitive, so match accordingly
382
+ actual_table_name = self.name
383
+ for table in available_tables:
384
+ if table.lower() == self.name.lower():
385
+ actual_table_name = table
386
+ break
387
+
388
+ return sa.Table(
389
+ actual_table_name,
390
+ self.container.sa_metadata,
391
+ autoload_with=sa_engine,
392
+ schema=schema,
393
+ )
394
+
395
+ def create_table(self, df: "pd.DataFrame | None" = None, **kwargs) -> None:
396
+ """handle if_exists='replace' with case-insensitive table names"""
397
+ if df is None:
398
+ df = pd.DataFrame(columns=self.columns)
399
+
400
+ # manually drop table for "replace" mode using case-insensitive matching
401
+ if kwargs.get("if_exists") == "replace":
402
+ with self.container.use_sa_engine(mode="write_data") as sa_engine:
403
+ inspector = sa.inspect(sa_engine)
404
+ # use default schema if dbschema is None
405
+ schema = self.container.dbschema or "public"
406
+ existing_tables = inspector.get_table_names(schema=schema)
407
+
408
+ # find table case-insensitively and drop using sqlalchemy
409
+ for t in existing_tables:
410
+ if t.lower() == self.name.lower():
411
+ # use sqlalchemy Table object for safe drop operation
412
+ table_to_drop = sa.Table(t, sa.MetaData(), schema=schema)
413
+ table_to_drop.drop(sa_engine, checkfirst=False)
414
+ break
415
+
416
+ kwargs["if_exists"] = "fail"
417
+
418
+ super().create_table(df, **kwargs)
419
+
420
+ def calculate_write_chunk_size(self, df: "pd.DataFrame") -> int:
421
+ """cap chunk size by redshift's 32767 parameter limit"""
422
+ # guard against empty dataframes
423
+ if len(df.columns) == 0:
424
+ return self.WRITE_CHUNK_SIZE
425
+
426
+ # calculate maximum rows based on parameter limit (32767 total params)
427
+ # each row uses len(df.columns) parameters
428
+ max_rows = 32767 // len(df.columns)
429
+ return min(self.WRITE_CHUNK_SIZE, max_rows)
430
+
431
+ def write_data(self, df: "pd.DataFrame", **kwargs):
432
+ self.INIT_WRITE_CHUNK = _init_worker # use custom init that suppresses warnings
433
+ super().write_data(df, **kwargs)
@@ -75,7 +75,7 @@ class DType(abc.ABC):
75
75
 
76
76
  def coerce(self, data: pd.Series) -> pd.Series:
77
77
  """
78
- Coerce a given the data to self's data type (expected to be overriden for each specific coercion)
78
+ Coerce a given the data to self's data type (expected to be overridden for each specific coercion).
79
79
  :param data: data
80
80
  :return: coerced pd.Series of data
81
81
  """
@@ -108,7 +108,7 @@ class DType(abc.ABC):
108
108
  return False # in case of a failure, be on the safer side
109
109
 
110
110
  def get_encompass_data_fallback_dtypes(self) -> list["DType"]:
111
- """Returns a default list of fallback dtypes for data encompassment (shall be overriden, when needed)"""
111
+ """Returns a default list of fallback dtypes for data encompassment (shall be overridden, when needed)."""
112
112
  return [VirtualVarchar]
113
113
 
114
114
  def encompass_data(
@@ -30,7 +30,7 @@ def handle_non_context_relations(
30
30
  data: pd.DataFrame,
31
31
  is_target: bool,
32
32
  ) -> pd.DataFrame:
33
- """Handle all non-context relations for a table"""
33
+ """Handle all non-context relations for a table."""
34
34
  non_context_relations = schema.subset(
35
35
  relation_type=NonContextRelation,
36
36
  relations_to=[table_name],
@@ -12,7 +12,7 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
- """Data pull."""
15
+ """Data pull utilities."""
16
16
 
17
17
  import itertools
18
18
  import json
@@ -655,7 +655,7 @@ def export_chunk(
655
655
  data_dir: Path,
656
656
  do_ctx_only: bool,
657
657
  ):
658
- """Distributes rows of a chunk into partitions using hash trick"""
658
+ """Distributes rows of a chunk into partitions using hash trick."""
659
659
 
660
660
  data_dir.mkdir(exist_ok=True, parents=True)
661
661
 
@@ -701,7 +701,7 @@ def export_chunk(
701
701
 
702
702
 
703
703
  def consolidate_partitions(data_dir: Path, shuffle: bool = True):
704
- """Consolidates partition chunks into partitions"""
704
+ """Consolidates partition chunks into partitions."""
705
705
  t0 = time.time()
706
706
  for partition_dir in sorted(d for d in data_dir.glob("part.*/") if d.is_dir()):
707
707
  partition_data = pd.concat(