-
Notifications
You must be signed in to change notification settings - Fork 13
Support for complex params #30
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
3ee757b
Support for complex params
jprakash-db 7b4cfe0
More tests
jprakash-db ee8cc29
Added better parsing
jprakash-db 50841bb
nit
jprakash-db dae6b3e
e2e tests
jprakash-db 514cfbc
nit
jprakash-db 192df14
Updated poetry.lock
jprakash-db 86223fb
poetry changes
jprakash-db 264c1fd
more tests
jprakash-db File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,10 @@ | ||
| from databricks.sqlalchemy.base import DatabricksDialect | ||
| from databricks.sqlalchemy._types import TINYINT, TIMESTAMP, TIMESTAMP_NTZ | ||
| from databricks.sqlalchemy._types import ( | ||
| TINYINT, | ||
| TIMESTAMP, | ||
| TIMESTAMP_NTZ, | ||
| DatabricksArray, | ||
| DatabricksMap, | ||
| ) | ||
|
|
||
| __all__ = ["TINYINT", "TIMESTAMP", "TIMESTAMP_NTZ"] | ||
| __all__ = ["TINYINT", "TIMESTAMP", "TIMESTAMP_NTZ", "DatabricksArray", "DatabricksMap"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,211 @@ | ||
| from .test_setup import TestSetup | ||
| from sqlalchemy import ( | ||
| Column, | ||
| BigInteger, | ||
| String, | ||
| Integer, | ||
| Numeric, | ||
| Boolean, | ||
| Date, | ||
| TIMESTAMP, | ||
| DateTime, | ||
| ) | ||
| from collections.abc import Sequence | ||
| from databricks.sqlalchemy import TIMESTAMP, TINYINT, DatabricksArray, DatabricksMap | ||
| from sqlalchemy.orm import DeclarativeBase, Session | ||
| from sqlalchemy import select | ||
| from datetime import date, datetime, time, timedelta, timezone | ||
| import pandas as pd | ||
| import numpy as np | ||
| import decimal | ||
|
|
||
|
|
||
| class TestComplexTypes(TestSetup): | ||
| def _parse_to_common_type(self, value): | ||
| """ | ||
| Function to convert the :value passed into a common python datatype for comparison | ||
|
|
||
| Convertion fyi | ||
| MAP Datatype on server is returned as a list of tuples | ||
| Ex: | ||
| {"a":1,"b":2} -> [("a",1),("b",2)] | ||
|
|
||
| ARRAY Datatype on server is returned as a numpy array | ||
| Ex: | ||
| ["a","b","c"] -> np.array(["a","b","c"],dtype=object) | ||
|
|
||
| Primitive datatype on server is returned as a numpy primitive | ||
| Ex: | ||
| 1 -> np.int64(1) | ||
| 2 -> np.int32(2) | ||
| """ | ||
| if value is None: | ||
| return None | ||
| elif isinstance(value, (Sequence, np.ndarray)) and not isinstance( | ||
| value, (str, bytes) | ||
| ): | ||
| return tuple(value) | ||
| elif isinstance(value, dict): | ||
| return tuple(value.items()) | ||
| elif isinstance(value, np.generic): | ||
| return value.item() | ||
| elif isinstance(value, decimal.Decimal): | ||
| return float(value) | ||
| else: | ||
| return value | ||
|
|
||
| def _recursive_compare(self, actual, expected): | ||
| """ | ||
| Function to compare the :actual and :expected values, recursively checks and ensures that all the data matches till the leaf level | ||
|
|
||
| Note: Complex datatype like MAP is not returned as a dictionary but as a list of tuples | ||
| """ | ||
| actual_parsed = self._parse_to_common_type(actual) | ||
| expected_parsed = self._parse_to_common_type(expected) | ||
|
|
||
| # Check if types are the same | ||
| if type(actual_parsed) != type(expected_parsed): | ||
| return False | ||
|
|
||
| # Handle lists or tuples | ||
| if isinstance(actual_parsed, (list, tuple)): | ||
| if len(actual_parsed) != len(expected_parsed): | ||
| return False | ||
| return all( | ||
| self._recursive_compare(o1, o2) | ||
| for o1, o2 in zip(actual_parsed, expected_parsed) | ||
| ) | ||
|
|
||
| return actual_parsed == expected_parsed | ||
|
|
||
| def sample_array_table(self) -> tuple[DeclarativeBase, dict]: | ||
| class Base(DeclarativeBase): | ||
| pass | ||
|
|
||
| class ArrayTable(Base): | ||
| __tablename__ = "sqlalchemy_array_table" | ||
|
|
||
| int_col = Column(Integer, primary_key=True) | ||
| array_int_col = Column(DatabricksArray(Integer)) | ||
| array_bigint_col = Column(DatabricksArray(BigInteger)) | ||
| array_numeric_col = Column(DatabricksArray(Numeric(10, 2))) | ||
| array_string_col = Column(DatabricksArray(String)) | ||
| array_boolean_col = Column(DatabricksArray(Boolean)) | ||
| array_date_col = Column(DatabricksArray(Date)) | ||
| array_datetime_col = Column(DatabricksArray(TIMESTAMP)) | ||
| array_datetime_col_ntz = Column(DatabricksArray(DateTime)) | ||
| array_tinyint_col = Column(DatabricksArray(TINYINT)) | ||
|
|
||
| sample_data = { | ||
| "int_col": 1, | ||
| "array_int_col": [1, 2], | ||
| "array_bigint_col": [1234567890123456789, 2345678901234567890], | ||
| "array_numeric_col": [1.1, 2.2], | ||
| "array_string_col": ["a", "b"], | ||
| "array_boolean_col": [True, False], | ||
| "array_date_col": [date(2020, 12, 25), date(2021, 1, 2)], | ||
| "array_datetime_col": [ | ||
| datetime(1991, 8, 3, 21, 30, 5, tzinfo=timezone(timedelta(hours=-8))), | ||
| datetime(1991, 8, 3, 21, 30, 5, tzinfo=timezone(timedelta(hours=-8))), | ||
| ], | ||
| "array_datetime_col_ntz": [ | ||
| datetime(1990, 12, 4, 6, 33, 41), | ||
| datetime(1990, 12, 4, 6, 33, 41), | ||
| ], | ||
| "array_tinyint_col": [-100, 100], | ||
| } | ||
|
|
||
| return ArrayTable, sample_data | ||
|
|
||
| def sample_map_table(self) -> tuple[DeclarativeBase, dict]: | ||
| class Base(DeclarativeBase): | ||
| pass | ||
|
|
||
| class MapTable(Base): | ||
| __tablename__ = "sqlalchemy_map_table" | ||
|
|
||
| int_col = Column(Integer, primary_key=True) | ||
| map_int_col = Column(DatabricksMap(Integer, Integer)) | ||
| map_bigint_col = Column(DatabricksMap(Integer, BigInteger)) | ||
| map_numeric_col = Column(DatabricksMap(Integer, Numeric(10, 2))) | ||
| map_string_col = Column(DatabricksMap(Integer, String)) | ||
| map_boolean_col = Column(DatabricksMap(Integer, Boolean)) | ||
| map_date_col = Column(DatabricksMap(Integer, Date)) | ||
| map_datetime_col = Column(DatabricksMap(Integer, TIMESTAMP)) | ||
| map_datetime_col_ntz = Column(DatabricksMap(Integer, DateTime)) | ||
| map_tinyint_col = Column(DatabricksMap(Integer, TINYINT)) | ||
|
|
||
| sample_data = { | ||
| "int_col": 1, | ||
| "map_int_col": {1: 1}, | ||
| "map_bigint_col": {1: 1234567890123456789}, | ||
| "map_numeric_col": {1: 1.1}, | ||
| "map_string_col": {1: "a"}, | ||
| "map_boolean_col": {1: True}, | ||
| "map_date_col": {1: date(2020, 12, 25)}, | ||
| "map_datetime_col": { | ||
| 1: datetime(1991, 8, 3, 21, 30, 5, tzinfo=timezone(timedelta(hours=-8))) | ||
| }, | ||
| "map_datetime_col_ntz": {1: datetime(1990, 12, 4, 6, 33, 41)}, | ||
| "map_tinyint_col": {1: -100}, | ||
| } | ||
|
|
||
| return MapTable, sample_data | ||
|
|
||
| def test_insert_array_table_sqlalchemy(self): | ||
| table, sample_data = self.sample_array_table() | ||
|
|
||
| with self.table_context(table) as engine: | ||
| sa_obj = table(**sample_data) | ||
| session = Session(engine) | ||
| session.add(sa_obj) | ||
| session.commit() | ||
|
|
||
| stmt = select(table).where(table.int_col == 1) | ||
|
|
||
| result = session.scalar(stmt) | ||
|
|
||
| compare = {key: getattr(result, key) for key in sample_data.keys()} | ||
| assert self._recursive_compare(compare, sample_data) | ||
|
|
||
| def test_insert_map_table_sqlalchemy(self): | ||
| table, sample_data = self.sample_map_table() | ||
|
|
||
| with self.table_context(table) as engine: | ||
| sa_obj = table(**sample_data) | ||
| session = Session(engine) | ||
| session.add(sa_obj) | ||
| session.commit() | ||
|
|
||
| stmt = select(table).where(table.int_col == 1) | ||
|
|
||
| result = session.scalar(stmt) | ||
|
|
||
| compare = {key: getattr(result, key) for key in sample_data.keys()} | ||
| assert self._recursive_compare(compare, sample_data) | ||
|
|
||
| def test_array_table_creation_pandas(self): | ||
| table, sample_data = self.sample_array_table() | ||
|
|
||
| with self.table_context(table) as engine: | ||
| # Insert the data into the table | ||
| df = pd.DataFrame([sample_data]) | ||
| df.to_sql(table.__tablename__, engine, if_exists="append", index=False) | ||
|
|
||
| # Read the data from the table | ||
| stmt = select(table) | ||
| df_result = pd.read_sql(stmt, engine) | ||
| assert self._recursive_compare(df_result.iloc[0].to_dict(), sample_data) | ||
|
|
||
| def test_map_table_creation_pandas(self): | ||
| table, sample_data = self.sample_map_table() | ||
|
|
||
| with self.table_context(table) as engine: | ||
| # Insert the data into the table | ||
| df = pd.DataFrame([sample_data]) | ||
| df.to_sql(table.__tablename__, engine, if_exists="append", index=False) | ||
|
|
||
| # Read the data from the table | ||
| stmt = select(table) | ||
| df_result = pd.read_sql(stmt, engine) | ||
| assert self._recursive_compare(df_result.iloc[0].to_dict(), sample_data) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| import pytest | ||
| from sqlalchemy import create_engine, Engine | ||
| from contextlib import contextmanager | ||
| from sqlalchemy.orm import DeclarativeBase, Session | ||
|
|
||
|
|
||
| class TestSetup: | ||
| @pytest.fixture(autouse=True) | ||
| def get_details(self, connection_details): | ||
| self.arguments = connection_details.copy() | ||
|
|
||
| def db_engine(self) -> Engine: | ||
| HOST = self.arguments["host"] | ||
| HTTP_PATH = self.arguments["http_path"] | ||
| ACCESS_TOKEN = self.arguments["access_token"] | ||
| CATALOG = self.arguments["catalog"] | ||
| SCHEMA = self.arguments["schema"] | ||
|
|
||
| connect_args = {"_user_agent_entry": "SQLAlchemy e2e Tests"} | ||
|
|
||
| conn_string = f"databricks://token:{ACCESS_TOKEN}@{HOST}?http_path={HTTP_PATH}&catalog={CATALOG}&schema={SCHEMA}" | ||
| return create_engine(conn_string, connect_args=connect_args) | ||
|
|
||
| @contextmanager | ||
| def table_context(self, table: DeclarativeBase): | ||
| engine = self.db_engine() | ||
| table.metadata.create_all(engine) | ||
| try: | ||
| yield engine | ||
| finally: | ||
| table.metadata.drop_all(engine) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.