├── test ├── __init__.py ├── pytest.ini ├── test_flight_dialect.py ├── conftest.py ├── test_dremio.py └── test_additional.py ├── MANIFEST.in ├── pyproject.toml ├── requirements_dev.txt ├── sqlalchemy_dremio ├── __init__.py ├── exceptions.py ├── flight_middleware.py ├── query.py ├── db.py ├── base.py └── flight.py ├── .editorconfig ├── setup.cfg ├── RELEASE_NOTES.md ├── .gitignore ├── scripts └── sample.sql ├── .github └── workflows │ └── dremio.yml ├── setup.py ├── README.md └── LICENSE /test/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include HISTORY.rst 2 | include LICENSE 3 | include README.rst 4 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.ruff] 2 | line-length = 100 3 | exclude = ["scripts"] 4 | 5 | -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | pytest~=8.4.1 2 | SQLAlchemy~=2.0.41 3 | pyarrow~=20.0.0 4 | bump-my-version>=1.2.0 5 | pandas>=2.2 6 | ruff>=0.1 7 | -------------------------------------------------------------------------------- /test/pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | log_cli = 1 3 | log_cli_level = INFO 4 | log_cli_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s) 5 | log_cli_date_format=%Y-%m-%d %H:%M:%S 6 | -------------------------------------------------------------------------------- /sqlalchemy_dremio/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '3.0.4' 2 | 3 | from .db import Connection as Connection, connect as connect 4 | from sqlalchemy.dialects import registry 5 | 6 | # Register the Flight end point 7 | registry.register("dremio+flight", "sqlalchemy_dremio.flight", "DremioDialect_flight") 8 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | charset = utf-8 11 | end_of_line = lf 12 | 13 | [*.bat] 14 | indent_style = tab 15 | end_of_line = crlf 16 | 17 | [LICENSE] 18 | insert_final_newline = false 19 | 20 | [Makefile] 21 | indent_style = tab 22 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 3.0.4 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:setup.py] 7 | search = version='{current_version}' 8 | replace = version='{new_version}' 9 | 10 | [bumpversion:file:sqlalchemy_dremio/__init__.py] 11 | search = __version__ = '{current_version}' 12 | replace = __version__ = '{new_version}' 13 | 14 | [bdist_wheel] 15 | universal = 1 16 | 17 | [db] 18 | default = dremio://dremio:dremio123@localhost:31010/dremio 19 | 20 | [egg_info] 21 | tag_build = 22 | tag_date = 0 23 | 24 | -------------------------------------------------------------------------------- /sqlalchemy_dremio/exceptions.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from __future__ import division 3 | from __future__ import print_function 4 | from __future__ import unicode_literals 5 | 6 | 7 | class Error(Exception): 8 | pass 9 | 10 | 11 | class Warning(Exception): 12 | pass 13 | 14 | 15 | class InterfaceError(Error): 16 | pass 17 | 18 | 19 | class DatabaseError(Error): 20 | pass 21 | 22 | 23 | class InternalError(DatabaseError): 24 | pass 25 | 26 | 27 | class OperationalError(DatabaseError): 28 | pass 29 | 30 | 31 | class ProgrammingError(DatabaseError): 32 | pass 33 | 34 | 35 | class IntegrityError(DatabaseError): 36 | pass 37 | 38 | 39 | class DataError(DatabaseError): 40 | pass 41 | 42 | 43 | class NotSupportedError(DatabaseError): 44 | pass 45 | -------------------------------------------------------------------------------- /RELEASE_NOTES.md: -------------------------------------------------------------------------------- 1 | ## Release 1.2.1 2 | 3 | - Single ticks in parametrized statements are escaped 4 | - Table name won't be fixed automatically if no schema is passed. The assumption is that the fully qualified path is properly escaped using quotes. Automated fixed paths lead to issues if a proper path is passed and it will break. 5 | 6 | ## Release 1.2.0 7 | 8 | - Replace parameterized statements by fully compiled, because Dremio does not support parameterized statements. 9 | - Bugfix in get_columns, when Schema is None, the schema "None" was prefixed 10 | - Alias `dialect` for `DremioDialect_pyodbc` created 11 | - Expose supported data types to pyodbc level, so that it works with "Great Expectations" 12 | - Introduced `?filter_schema_names=Space1.Folder1,Space2.Folder2` parameter to filter schemas. If the parameter is not set, all schemas will be returned 13 | - Added has_table implementation for dialect, which seems to be required by latest Apache Superset 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | venv/ 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | .idea/ 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *,cover 48 | .hypothesis/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | 57 | # Sphinx documentation 58 | docs/_build/ 59 | 60 | # PyBuilder 61 | target/ 62 | 63 | # pyenv python configuration file 64 | .python-version 65 | -------------------------------------------------------------------------------- /scripts/sample.sql: -------------------------------------------------------------------------------- 1 | -- SQL Alchemy test suite set up 2 | CREATE TABLE $scratch.sqlalchemy_tests 3 | as 4 | (SELECT 5 | -- Numbers 6 | 1 AS int_col, CAST(81297389127389213 AS BIGINT) AS bigint_col, 7 | 9112.229 AS decimal_col, 8 | CAST(9192.922 AS FLOAT) AS float_col, 9 | CAST(9292.17272 AS DOUBLE) AS double_col, 10 | -- String 11 | 'ZZZZZZZZZZZZ' AS varchar_col, binary_string('AAAAAAAAA') AS binary_col, 12 | -- Date/TS 13 | NOW() AS timestamp_col, to_date('2020-04-05','yyyy-mm-dd') AS date_col, CAST('12:19' AS TIME) AS time_col, 14 | -- Boolean 15 | true as bool_col) UNION ALL 16 | (SELECT 17 | -- Numbers 18 | 2 AS int_col, CAST(812123489127389213 AS BIGINT) AS bigint_col, 19 | 6782.229 AS decimal_col, 20 | CAST(2234192.922 AS FLOAT) AS float_col, 21 | CAST(9122922.17272 AS DOUBLE) AS double_col, 22 | -- String 23 | 'BBBBBBBBB' AS varchar_col, binary_string('CCCCCCCCCCCC') AS binary_col, 24 | -- Date/TS 25 | NOW() AS timestamp_col, to_date('2022-04-05','yyyy-mm-dd') AS date_col, CAST('10:19' AS TIME) AS time_col, 26 | -- Boolean 27 | false AS bool_col); 28 | -- To Query the table 29 | -- SELECT * FROM $scratch.sqlalchemy_tests; 30 | -- Describe 31 | -- DESC $scratch.sqlalchemy_tests; 32 | -- Drop 33 | -- DROP TABLE $scratch.sqlalchemy_tests; 34 | -------------------------------------------------------------------------------- /test/test_flight_dialect.py: -------------------------------------------------------------------------------- 1 | import sqlalchemy.engine.url as url 2 | 3 | from sqlalchemy_dremio.flight import DremioDialect_flight 4 | 5 | 6 | def _connect_args(connect_url: str) -> list[str]: 7 | dialect = DremioDialect_flight() 8 | args, kwargs = dialect.create_connect_args(url.make_url(connect_url)) 9 | assert kwargs == {} 10 | return args[0].split(";") 11 | 12 | 13 | def test_create_connect_args_basic(): 14 | connectors = _connect_args("dremio+flight://localhost:31010") 15 | assert connectors == ["HOST=localhost", "PORT=31010"] 16 | 17 | 18 | def test_create_connect_args_with_user_and_db(): 19 | connectors = _connect_args( 20 | "dremio+flight://user:pass@localhost:32010/dremio" 21 | ) 22 | assert "UID=user" in connectors 23 | assert "PWD=pass" in connectors 24 | assert "Schema=dremio" in connectors 25 | assert "HOST=localhost" in connectors 26 | assert "PORT=32010" in connectors 27 | 28 | 29 | def test_create_connect_args_query_options_case_insensitive(): 30 | connectors = _connect_args( 31 | "dremio+flight://localhost:12345/db?useencryption=false&routing_engine=myeng" 32 | ) 33 | assert "UseEncryption=false" in connectors 34 | assert "routing_engine=myeng" in connectors 35 | 36 | -------------------------------------------------------------------------------- /.github/workflows/dremio.yml: -------------------------------------------------------------------------------- 1 | name: Dremio Integration Tests 2 | 3 | on: 4 | workflow_dispatch: 5 | pull_request: 6 | push: 7 | branches: [ master ] 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | services: 13 | dremio: 14 | image: dremio/dremio-oss:latest 15 | env: 16 | DREMIO_JAVA_EXTRA_OPTS: "-Ddebug.addDefaultUser=true" 17 | ports: 18 | - 9047:9047 19 | - 31010:31010 20 | - 32010:32010 21 | steps: 22 | - uses: actions/checkout@v4 23 | - name: Set up Python 3.14 24 | uses: actions/setup-python@v5 25 | with: 26 | python-version: 3.13 27 | - name: Install dependencies 28 | run: | 29 | pip install -r requirements_dev.txt 30 | - name: Wait for Dremio 31 | run: | 32 | for i in {1..60}; do 33 | curl -f http://localhost:9047/ || true 34 | if [ $? -eq 0 ]; then break; fi 35 | sleep 5 36 | done 37 | - name: Install dialect 38 | run: pip install -e . 39 | - name: Run tests 40 | env: 41 | DREMIO_CONNECTION_URL: dremio+flight://dremio:dremio123@localhost:32010/dremio?UseEncryption=false 42 | run: | 43 | pytest 44 | -------------------------------------------------------------------------------- /sqlalchemy_dremio/flight_middleware.py: -------------------------------------------------------------------------------- 1 | from pyarrow.flight import ClientMiddleware 2 | from pyarrow.flight import ClientMiddlewareFactory 3 | from http.cookies import SimpleCookie 4 | 5 | 6 | class CookieMiddlewareFactory(ClientMiddlewareFactory): 7 | """A factory that creates CookieMiddleware(s).""" 8 | 9 | def __init__(self): 10 | self.cookies = {} 11 | 12 | def start_call(self, info): 13 | return CookieMiddleware(self) 14 | 15 | class CookieMiddleware(ClientMiddleware): 16 | """ 17 | A ClientMiddleware that receives and retransmits cookies. 18 | For simplicity, this does not auto-expire cookies. 19 | Parameters 20 | ---------- 21 | factory : CookieMiddlewareFactory 22 | The factory containing the currently cached cookies. 23 | """ 24 | 25 | def __init__(self, factory): 26 | self.factory = factory 27 | 28 | def received_headers(self, headers): 29 | for key in headers: 30 | if key.lower() == 'set-cookie': 31 | cookie = SimpleCookie() 32 | for item in headers.get(key): 33 | cookie.load(item) 34 | 35 | self.factory.cookies.update(cookie.items()) 36 | 37 | def sending_headers(self): 38 | if self.factory.cookies: 39 | cookie_string = '; '.join("{!s}={!s}".format(key, val.value) for (key, val) in self.factory.cookies.items()) 40 | return {b'cookie': cookie_string.encode('utf-8')} 41 | return {} 42 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """The setup script.""" 5 | 6 | from setuptools import setup, find_packages 7 | 8 | with open('README.md') as readme_file: 9 | readme = readme_file.read() 10 | 11 | requirements = [ 12 | 'SQLAlchemy~=2.0.41', 13 | 'pyarrow~=20.0.0' 14 | ] 15 | 16 | setup_requirements = [ 17 | ] 18 | 19 | test_requirements = [ 20 | ] 21 | 22 | setup( 23 | name='sqlalchemy_dremio', 24 | version='3.0.4', 25 | description="A SQLAlchemy dialect for Dremio via the Flight interface.", 26 | long_description=readme, 27 | long_description_content_type='text/markdown', 28 | author="Naren", 29 | author_email='me@narendran.info', 30 | url='https://github.com/narendrans/sqlalchemy_dremio', 31 | packages=find_packages(include=['sqlalchemy_dremio']), 32 | entry_points={ 33 | 'sqlalchemy.dialects': [ 34 | 'dremio.flight = sqlalchemy_dremio.flight:DremioDialect_flight', 35 | ] 36 | }, 37 | include_package_data=True, 38 | install_requires=requirements, 39 | license="Apache Software License", 40 | zip_safe=False, 41 | keywords='sqlalchemy_dremio', 42 | classifiers=[ 43 | 'Development Status :: 5 - Production/Stable', 44 | 'Intended Audience :: Developers', 45 | 'License :: OSI Approved :: Apache Software License', 46 | 'Natural Language :: English', 47 | 'Programming Language :: Python :: 3', 48 | 'Programming Language :: Python :: 3.7' 49 | ] 50 | ) 51 | -------------------------------------------------------------------------------- /test/conftest.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pathlib import Path 3 | 4 | import pytest 5 | from sqlalchemy import create_engine, text 6 | import sqlalchemy.dialects 7 | 8 | sqlalchemy.dialects.registry.register( 9 | "dremio", "sqlalchemy_dremio.flight", "DremioDialect_flight" 10 | ) 11 | 12 | def _help(): 13 | print( 14 | """Set the connection string as an env var, e.g. 15 | Windows: setx DREMIO_CONNECTION_URL "dremio+flight://dremio:dremio123@localhost:32010/dremio" 16 | Linux/macOS: export DREMIO_CONNECTION_URL="dremio+flight://dremio:dremio123@localhost:32010/dremio" 17 | """ 18 | ) 19 | 20 | def get_engine(): 21 | url = os.getenv("DREMIO_CONNECTION_URL") 22 | if not url: 23 | return None 24 | return create_engine(url, future=True) # future-style API 25 | 26 | @pytest.fixture(scope="session", autouse=True) 27 | def init_test_schema(request): 28 | engine = get_engine() 29 | if engine is None: 30 | return 31 | 32 | sql = Path("scripts/sample.sql").read_text() 33 | 34 | # run sample.sql inside a transaction 35 | with engine.begin() as conn: # -> Connection object 36 | conn.execute(text(sql)) 37 | 38 | def fin(): 39 | if engine is None: 40 | return 41 | with engine.begin() as conn: 42 | conn.execute(text('DROP TABLE IF EXISTS "$scratch"."sqlalchemy_tests"')) 43 | 44 | request.addfinalizer(fin) 45 | 46 | @pytest.fixture(scope="session") 47 | def engine(): 48 | """Re-export the session-wide engine for tests that need it.""" 49 | return get_engine() 50 | -------------------------------------------------------------------------------- /test/test_dremio.py: -------------------------------------------------------------------------------- 1 | # test/test_dremio.py 2 | from sqlalchemy import text 3 | from . import conftest 4 | 5 | 6 | def _conn(): 7 | engine = conftest.get_engine() 8 | if engine is None: 9 | import pytest 10 | pytest.skip("DREMIO_CONNECTION_URL not set") 11 | return engine.connect() 12 | 13 | 14 | def _quote(ident: str) -> str: 15 | """Minimal quoting to prevent breaking the INFORMATION_SCHEMA query.""" 16 | return ident.replace('"', '""') 17 | 18 | 19 | def _table_exists(table: str, schema: str | None = None) -> bool: 20 | tbl = _quote(table) 21 | if schema: 22 | sch = _quote(schema) 23 | sql = ( 24 | 'SELECT COUNT(*) AS cnt FROM INFORMATION_SCHEMA."TABLES" ' 25 | f"WHERE TABLE_NAME = '{tbl}' AND TABLE_SCHEMA = '{sch}'" 26 | ) 27 | else: 28 | sql = ( 29 | 'SELECT COUNT(*) AS cnt FROM INFORMATION_SCHEMA."TABLES" ' 30 | f"WHERE TABLE_NAME = '{tbl}'" 31 | ) 32 | with _conn() as c: 33 | return c.execute(text(sql)).fetchone()[0] > 0 34 | 35 | 36 | def test_connect_args(): 37 | with _conn() as c: 38 | version = c.execute(text("SELECT version FROM sys.version")).fetchone()[0] 39 | assert version 40 | 41 | 42 | def test_simple_sql(): 43 | with _conn() as c: 44 | dbs = c.execute(text("SHOW DATABASES")).all() 45 | assert dbs 46 | 47 | 48 | def test_row_count(): 49 | with _conn() as c: 50 | cnt = c.execute( 51 | text('SELECT COUNT(*) FROM "$scratch"."sqlalchemy_tests"') 52 | ).fetchone()[0] 53 | assert cnt > 0 54 | 55 | 56 | def test_has_table_True(): 57 | assert _table_exists("version", "sys") 58 | 59 | 60 | def test_has_table_True2(): 61 | assert _table_exists("version") 62 | 63 | 64 | def test_has_table_False(): 65 | assert not _table_exists("does_not_exist", "sys") 66 | 67 | 68 | def test_has_table_False2(): 69 | assert not _table_exists("does_not_exist") 70 | -------------------------------------------------------------------------------- /sqlalchemy_dremio/query.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from __future__ import division 3 | from __future__ import print_function 4 | from __future__ import unicode_literals 5 | 6 | from sqlalchemy import types 7 | 8 | import pyarrow as pa 9 | from pyarrow import flight 10 | 11 | _type_map = { 12 | 'boolean': types.BOOLEAN, 13 | 'BOOLEAN': types.BOOLEAN, 14 | 'bool': types.BOOLEAN, 15 | 'varbinary': types.LargeBinary, 16 | 'VARBINARY': types.LargeBinary, 17 | 'date': types.DATE, 18 | 'DATE': types.DATE, 19 | 'float64': types.FLOAT, 20 | 'float32': types.FLOAT, 21 | 'decimal': types.DECIMAL, 22 | 'DECIMAL': types.DECIMAL, 23 | 'double': types.FLOAT, 24 | 'DOUBLE': types.FLOAT, 25 | 'interval': types.Interval, 26 | 'INTERVAL': types.Interval, 27 | 'int32': types.INTEGER, 28 | 'int64': types.BIGINT, 29 | 'time': types.TIME, 30 | 'TIME': types.TIME, 31 | 'datetime64[ns]': types.DATETIME, 32 | 'datetime64[ms]': types.DATETIME, 33 | 'timestamp': types.TIMESTAMP, 34 | 'TIMESTAMP': types.TIMESTAMP, 35 | 'varchar': types.VARCHAR, 36 | 'VARCHAR': types.VARCHAR, 37 | 'smallint': types.SMALLINT, 38 | 'CHARACTER VARYING': types.VARCHAR, 39 | 'object': types.VARCHAR 40 | } 41 | 42 | 43 | def run_query(query, flightclient=None, options=None): 44 | info = flightclient.get_flight_info(flight.FlightDescriptor.for_command(query), options) 45 | reader = flightclient.do_get(info.endpoints[0].ticket, options) 46 | 47 | batches = [] 48 | while True: 49 | try: 50 | batch, metadata = reader.read_chunk() 51 | batches.append(batch) 52 | except StopIteration: 53 | break 54 | 55 | data = pa.Table.from_batches(batches) 56 | df = data.to_pandas() 57 | 58 | return df 59 | 60 | 61 | def execute(query, flightclient=None, options=None): 62 | df = run_query(query, flightclient, options) 63 | 64 | result = [] 65 | 66 | for x, y in df.dtypes.to_dict().items(): 67 | o = (x, _type_map[str(y.name)], None, None, True) 68 | result.append(o) 69 | 70 | return df.values.tolist(), result 71 | -------------------------------------------------------------------------------- /test/test_additional.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from sqlalchemy_dremio.flight import DremioDialect_flight 3 | from sqlalchemy_dremio.flight_middleware import CookieMiddlewareFactory 4 | import sqlalchemy.engine.url as sa_url 5 | from sqlalchemy_dremio import db 6 | from sqlalchemy_dremio.exceptions import NotSupportedError 7 | 8 | 9 | def test_create_connect_args_all_options(): 10 | conn_url = ( 11 | "dremio+flight://localhost:32010/db" 12 | "?UseEncryption=false&DisableCertificateVerification=true" 13 | "&TrustedCerts=/tmp/ca.pem&routing_queue=prod&routing_tag=tag1" 14 | ""ing=double&routing_engine=engine1&Token=mytoken" 15 | ) 16 | dialect = DremioDialect_flight() 17 | args, kwargs = dialect.create_connect_args(sa_url.make_url(conn_url)) 18 | connectors = args[0].split(";") 19 | assert "HOST=localhost" in connectors 20 | assert "PORT=32010" in connectors 21 | assert "Schema=db" in connectors 22 | assert "UseEncryption=false" in connectors 23 | assert "DisableCertificateVerification=true" in connectors 24 | assert "TrustedCerts=/tmp/ca.pem" in connectors 25 | assert "routing_queue=prod" in connectors 26 | assert "routing_tag=tag1" in connectors 27 | assert "quoting=double" in connectors 28 | assert "routing_engine=engine1" in connectors 29 | assert "Token=mytoken" in connectors 30 | assert kwargs == {} 31 | 32 | 33 | def test_cursor_fetch_methods(monkeypatch): 34 | cursor = db.Cursor(flightclient=None, options=None) 35 | 36 | def fake_execute(sql, flightclient=None, options=None): 37 | return [[[1]], [("a", None, None, None, True)]] 38 | 39 | monkeypatch.setattr(db, "execute", fake_execute) 40 | 41 | cursor.execute("SELECT 1") 42 | assert cursor.rowcount == 1 43 | assert cursor.fetchone() == [1] 44 | assert cursor.fetchone() is None 45 | cursor._results = [[2], [3]] 46 | assert cursor.fetchmany(size=1) == [[2]] 47 | assert cursor.fetchall() == [[3]] 48 | 49 | 50 | def test_cursor_executemany_not_supported(): 51 | cursor = db.Cursor(flightclient=None, options=None) 52 | with pytest.raises(NotSupportedError): 53 | cursor.executemany("SELECT 1", [(1,)]) 54 | 55 | 56 | def test_cookie_middleware_roundtrip(): 57 | factory = CookieMiddlewareFactory() 58 | middleware = factory.start_call(None) 59 | middleware.received_headers({"set-cookie": ["a=1", "b=2"]}) 60 | headers = middleware.sending_headers() 61 | assert headers == {b"cookie": b"a=1; b=2"} 62 | 63 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SQLAlchemy Dremio 2 | 3 | 4 | ![PyPI](https://img.shields.io/pypi/v/sqlalchemy_dremio.svg) 5 | ![CI](https://github.com/narendrans/sqlalchemy_dremio/actions/workflows/dremio.yml/badge.svg) 6 | 7 | A SQLAlchemy dialect for Dremio via ODBC and Flight interfaces. 8 | 9 | 10 | * [Installation](#installation) 11 | * [Usage](#usage) 12 | * [Testing](#testing) 13 | * [Superset Integration](#superset-integration) 14 | 15 | 16 | Installation 17 | ------------ 18 | 19 | From pip: 20 | ----------- 21 | 22 | `pip install sqlalchemy_dremio` 23 | 24 | Or from conda: 25 | -------------- 26 | `conda install sqlalchemy-dremio` 27 | 28 | To install from source: 29 | `python setup.py install` 30 | 31 | Usage 32 | ----- 33 | 34 | Connection String example: 35 | 36 | Dremio Software: 37 | 38 | `dremio+flight://user:password@host:port/dremio` 39 | 40 | Dremio Cloud: 41 | 42 | `dremio+flight://data.dremio.cloud:443/?Token=UseEncryption=true&disableCertificateVerification=true` 43 | 44 | Options: 45 | 46 | Schema - (Optional) The schema to use 47 | 48 | TLS: 49 | 50 | UseEncryption=true|false - (Optional) Enables TLS connection. Must be enabled on Dremio to use it. 51 | DisableCertificateVerification=true|false - (Optional) Disables certificate verification. 52 | 53 | WLM: 54 | 55 | https://docs.dremio.com/software/advanced-administration/workload-management/#query-tagging--direct-routing-configuration 56 | 57 | 58 | routing_queue - (Optional) The queue in which queries should run 59 | routing_tag - (Optional) Routing tag to use. 60 | routing_engine - (Optional) The engine in which the queries should run 61 | 62 | Testing 63 | ------- 64 | 65 | You can run the integration tests with the Dremio community edition Docker image. 66 | 67 | ```bash 68 | docker run -d -p 9047:9047 -p 31010:31010 -p 32010:32010 --name dremio dremio/dremio-oss:latest 69 | export DREMIO_CONNECTION_URL="dremio+flight://dremio:dremio123@localhost:32010/dremio?UseEncryption=false" 70 | pytest 71 | ``` 72 | 73 | The workflow in `.github/workflows/dremio.yml` demonstrates how to run these tests automatically on GitHub Actions. 74 | The CI badge at the top of this file shows the current test status. 75 | 76 | Superset Integration 77 | ------------- 78 | 79 | The ODBC connection to superset is now deprecated. Please update sqlalchemy_dremio to 3.0.2 to use the flight connection. 80 | 81 | Release Notes 82 | ------------- 83 | 84 | 3.0.4 85 | ----- 86 | - Addressing issue #34 and #37: Add driver name to dialects 87 | 88 | 3.0.3 89 | ----- 90 | - Add back missing routing_engine property. 91 | 92 | 3.0.2 93 | ----- 94 | - Add implementations of has_table and get_view_names. 95 | 96 | 3.0.1 97 | ----- 98 | - Made connection string property keys case-insensitive 99 | - Fix incorrect lookup of the token property 100 | - Fix incorrect lookup of the DisableCertificateVerification property 101 | -------------------------------------------------------------------------------- /sqlalchemy_dremio/db.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from __future__ import division 3 | from __future__ import print_function 4 | from __future__ import unicode_literals 5 | 6 | import logging 7 | 8 | from pyarrow import flight 9 | 10 | from sqlalchemy_dremio.exceptions import Error, NotSupportedError 11 | from sqlalchemy_dremio.flight_middleware import CookieMiddlewareFactory 12 | from sqlalchemy_dremio.query import execute 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | paramstyle = 'qmark' 17 | 18 | 19 | def connect(c): 20 | return Connection(c) 21 | 22 | 23 | def check_closed(f): 24 | """Decorator that checks if connection/cursor is closed.""" 25 | 26 | def g(self, *args, **kwargs): 27 | if self.closed: 28 | raise Error( 29 | '{klass} already closed'.format(klass=self.__class__.__name__)) 30 | return f(self, *args, **kwargs) 31 | 32 | return g 33 | 34 | 35 | def check_result(f): 36 | """Decorator that checks if the cursor has results from `execute`.""" 37 | 38 | def d(self, *args, **kwargs): 39 | if self._results is None: 40 | raise Error('Called before `execute`') 41 | return f(self, *args, **kwargs) 42 | 43 | return d 44 | 45 | 46 | class Connection(object): 47 | 48 | def __init__(self, connection_string): 49 | 50 | # Build a map from the connection string supplied using the SQLAlchemy URI 51 | # and supplied properties. The format is generated from DremioDialect_flight.create_connect_args() 52 | # and is a semi-colon delimited string of key=value pairs. Note that the value itself can 53 | # contain equal signs. 54 | properties = {} 55 | splits = connection_string.split(";") 56 | 57 | for kvpair in splits: 58 | kv = kvpair.split("=",1) 59 | properties[kv[0]] = kv[1] 60 | 61 | connection_args = {} 62 | 63 | # Connect to the server endpoint with an encrypted TLS connection by default. 64 | protocol = 'tls' 65 | if 'UseEncryption' in properties and properties['UseEncryption'].lower() == 'false': 66 | protocol = 'tcp' 67 | else: 68 | # Specify the trusted certificates 69 | connection_args['disable_server_verification'] = False 70 | if 'TrustedCerts' in properties: 71 | with open(properties['TrustedCerts'] , "rb") as root_certs: 72 | connection_args["tls_root_certs"] = root_certs.read() 73 | # Or disable server verification entirely 74 | elif 'DisableCertificateVerification' in properties and properties['DisableCertificateVerification'].lower() == 'true': 75 | connection_args['disable_server_verification'] = True 76 | 77 | # Enabling cookie middleware for stateful connectivity. 78 | client_cookie_middleware = CookieMiddlewareFactory() 79 | 80 | client = flight.FlightClient('grpc+{0}://{1}:{2}'.format(protocol, properties['HOST'], properties['PORT']), 81 | middleware=[client_cookie_middleware], **connection_args) 82 | 83 | # Authenticate either using basic username/password or using the Token parameter. 84 | headers = [] 85 | if 'UID' in properties: 86 | bearer_token = client.authenticate_basic_token(properties['UID'], properties['PWD']) 87 | headers.append(bearer_token) 88 | else: 89 | headers.append((b'authorization', "Bearer {}".format(properties['Token']).encode('utf-8'))) 90 | 91 | # Propagate Dremio-specific headers. 92 | def add_header(properties, headers, header_name): 93 | if header_name in properties: 94 | headers.append((header_name.lower().encode('utf-8'), properties[header_name].encode('utf-8'))) 95 | 96 | add_header(properties, headers, 'Schema') 97 | add_header(properties, headers, 'routing_queue') 98 | add_header(properties, headers, 'routing_tag') 99 | add_header(properties, headers, 'quoting') 100 | add_header(properties, headers, 'routing_engine') 101 | 102 | self.flightclient = client 103 | self.options = flight.FlightCallOptions(headers=headers) 104 | 105 | self.closed = False 106 | self.cursors = [] 107 | 108 | @check_closed 109 | def rollback(self): 110 | pass 111 | 112 | @check_closed 113 | def close(self): 114 | """Close the connection now.""" 115 | self.closed = True 116 | for cursor in self.cursors: 117 | try: 118 | cursor.close() 119 | except Error: 120 | pass # already closed 121 | 122 | @check_closed 123 | def commit(self): 124 | pass 125 | 126 | @check_closed 127 | def cursor(self): 128 | """Return a new Cursor Object using the connection.""" 129 | cursor = Cursor(self.flightclient, self.options) 130 | self.cursors.append(cursor) 131 | 132 | return cursor 133 | 134 | @check_closed 135 | def execute(self, query): 136 | cursor = self.cursor() 137 | return cursor.execute(query) 138 | 139 | def __enter__(self): 140 | return self 141 | 142 | def __exit__(self, *exc): 143 | self.commit() # no-op 144 | self.close() 145 | 146 | 147 | class Cursor(object): 148 | """Connection cursor.""" 149 | 150 | def __init__(self, flightclient=None, options=None): 151 | self.flightclient = flightclient 152 | self.options = options 153 | 154 | # This read/write attribute specifies the number of rows to fetch at a 155 | # time with .fetchmany(). It defaults to 1 meaning to fetch a single 156 | # row at a time. 157 | self.arraysize = 1 158 | 159 | self.closed = False 160 | 161 | # this is updated only after a query 162 | self.description = None 163 | 164 | # this is set to a list of rows after a successful query 165 | self._results = None 166 | 167 | @property 168 | @check_result 169 | @check_closed 170 | def rowcount(self): 171 | return len(self._results) 172 | 173 | @check_closed 174 | def close(self): 175 | """Close the cursor.""" 176 | self.closed = True 177 | 178 | @check_closed 179 | def execute(self, query, params=None): 180 | self.description = None 181 | self._results, self.description = execute( 182 | query, self.flightclient, self.options) 183 | return self 184 | 185 | @check_closed 186 | def executemany(self, query, seq_of_parameters=None): 187 | """Compatibility wrapper for DBAPI executemany. 188 | 189 | ``df.to_sql`` and other helpers expect the ``executemany`` method to 190 | accept the SQL statement and a sequence of parameters. Dremio does not 191 | support parameterized execution, so this method simply raises a 192 | ``NotSupportedError`` regardless of the parameters passed. 193 | """ 194 | 195 | raise NotSupportedError( 196 | '`executemany` is not supported, use `execute` instead') 197 | 198 | @check_result 199 | @check_closed 200 | def fetchone(self): 201 | """ 202 | Fetch the next row of a query result set, returning a single sequence, 203 | or `None` when no more data is available. 204 | """ 205 | try: 206 | return self._results.pop(0) 207 | except IndexError: 208 | return None 209 | 210 | @check_result 211 | @check_closed 212 | def fetchmany(self, size=None): 213 | """ 214 | Fetch the next set of rows of a query result, returning a sequence of 215 | sequences (e.g. a list of tuples). An empty sequence is returned when 216 | no more rows are available. 217 | """ 218 | size = size or self.arraysize 219 | out = self._results[:size] 220 | self._results = self._results[size:] 221 | return out 222 | 223 | @check_result 224 | @check_closed 225 | def fetchall(self): 226 | """ 227 | Fetch all (remaining) rows of a query result, returning them as a 228 | sequence of sequences (e.g. a list of tuples). Note that the cursor's 229 | arraysize attribute can affect the performance of this operation. 230 | """ 231 | out = self._results[:] 232 | self._results = [] 233 | return out 234 | 235 | @check_closed 236 | def setinputsizes(self, sizes): 237 | # not supported 238 | pass 239 | 240 | @check_closed 241 | def setoutputsizes(self, sizes): 242 | # not supported 243 | pass 244 | 245 | @check_closed 246 | def __iter__(self): 247 | return iter(self._results) 248 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | ============================================================================ 204 | APACHE SUPERSET SUBCOMPONENTS: 205 | 206 | The Apache Superset project contains subcomponents with separate copyright 207 | notices and license terms. Your use of the source code for the these 208 | subcomponents is subject to the terms and conditions of the following 209 | licenses. 210 | 211 | ======================================================================== 212 | Third party SIL Open Font License v1.1 (OFL-1.1) 213 | ======================================================================== 214 | 215 | (SIL OPEN FONT LICENSE Version 1.1) The Inter font family (https://github.com/rsms/inter) 216 | (SIL OPEN FONT LICENSE Version 1.1) The Fira Code font family (https://github.com/tonsky/FiraCode) -------------------------------------------------------------------------------- /sqlalchemy_dremio/base.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import schema, types, pool 2 | from sqlalchemy.engine import default, reflection 3 | from sqlalchemy.sql import compiler 4 | 5 | _dialect_name = "dremio" 6 | 7 | _type_map = { 8 | 'boolean': types.BOOLEAN, 9 | 'BOOLEAN': types.BOOLEAN, 10 | 'varbinary': types.LargeBinary, 11 | 'VARBINARY': types.LargeBinary, 12 | 'date': types.DATE, 13 | 'DATE': types.DATE, 14 | 'float': types.FLOAT, 15 | 'FLOAT': types.FLOAT, 16 | 'decimal': types.DECIMAL, 17 | 'DECIMAL': types.DECIMAL, 18 | 'double': types.FLOAT, 19 | 'DOUBLE': types.FLOAT, 20 | 'interval': types.Interval, 21 | 'INTERVAL': types.Interval, 22 | 'int': types.INTEGER, 23 | 'INT': types.INTEGER, 24 | 'integer': types.INTEGER, 25 | 'INTEGER': types.INTEGER, 26 | 'bigint': types.BIGINT, 27 | 'BIGINT': types.BIGINT, 28 | 'time': types.TIME, 29 | 'TIME': types.TIME, 30 | 'timestamp': types.TIMESTAMP, 31 | 'TIMESTAMP': types.TIMESTAMP, 32 | 'varchar': types.VARCHAR, 33 | 'VARCHAR': types.VARCHAR, 34 | 'smallint': types.SMALLINT, 35 | 'CHARACTER VARYING': types.VARCHAR, 36 | 'ANY': types.VARCHAR, 37 | 38 | 'ARRAY': types.ARRAY, 39 | 'ROW': types.JSON, 40 | 'BINARY VARYING': types.LargeBinary, 41 | } 42 | 43 | 44 | class DremioExecutionContext(default.DefaultExecutionContext): 45 | pass 46 | 47 | 48 | class DremioCompiler(compiler.SQLCompiler): 49 | def visit_char_length_func(self, fn, **kw): 50 | return 'length{}'.format(self.function_argspec(fn, **kw)) 51 | 52 | def visit_table(self, table, asfrom=False, **kwargs): 53 | 54 | if asfrom: 55 | if table.schema is not None and table.schema != "": 56 | fixed_schema = ".".join(["\"" + i.replace('"', '') + "\"" for i in table.schema.split(".")]) 57 | fixed_table = fixed_schema + ".\"" + table.name.replace("\"", "") + "\"" 58 | else: 59 | # don't change anything. expect a fully and properly qualified path if no schema is passed. 60 | fixed_table = table.name 61 | # fixed_table = "\"" + table.name.replace("\"", "") + "\"" 62 | return fixed_table 63 | else: 64 | return "" 65 | 66 | def visit_tablesample(self, tablesample, asfrom=False, **kw): 67 | print(tablesample) 68 | 69 | 70 | class DremioDDLCompiler(compiler.DDLCompiler): 71 | def get_column_specification(self, column, **kwargs): 72 | colspec = self.preparer.format_column(column) 73 | colspec += " " + self.dialect.type_compiler.process(column.type) 74 | if column is column.table._autoincrement_column and \ 75 | True and \ 76 | ( 77 | column.default is None or \ 78 | isinstance(column.default, schema.Sequence) 79 | ): 80 | colspec += " IDENTITY" 81 | if isinstance(column.default, schema.Sequence) and \ 82 | column.default.start > 0: 83 | colspec += " " + str(column.default.start) 84 | else: 85 | default = self.get_column_default_string(column) 86 | if default is not None: 87 | colspec += " DEFAULT " + default 88 | 89 | if not column.nullable: 90 | colspec += " NOT NULL" 91 | return colspec 92 | 93 | 94 | class DremioIdentifierPreparer(compiler.IdentifierPreparer): 95 | reserved_words = compiler.RESERVED_WORDS.copy() 96 | dremio_reserved = {'abs', 'all', 'allocate', 'allow', 'alter', 'and', 'any', 'are', 'array', 97 | 'array_max_cardinality', 'as', 'asensitivelo', 'asymmetric', 'at', 'atomic', 'authorization', 98 | 'avg', 'begin', 'begin_frame', 'begin_partition', 'between', 'bigint', 'binary', 'bit', 'blob', 99 | 'boolean', 'both', 'by', 'call', 'called', 'cardinality', 'cascaded', 'case', 'cast', 'ceil', 100 | 'ceiling', 'char', 'char_length', 'character', 'character_length', 'check', 'classifier', 101 | 'clob', 'close', 'coalesce', 'collate', 'collect', 'column', 'commit', 'condition', 'connect', 102 | 'constraint', 'contains', 'convert', 'corr', 'corresponding', 'count', 'covar_pop', 103 | 'covar_samp', 'create', 'cross', 'cube', 'cume_dist', 'current', 'current_catalog', 104 | 'current_date', 'current_default_transform_group', 'current_path', 'current_role', 105 | 'current_row', 'current_schema', 'current_time', 'current_timestamp', 106 | 'current_transform_group_for_type', 'current_user', 'cursor', 'cycle', 'date', 'day', 107 | 'deallocate', 'dec', 'decimal', 'declare', 'default', 'define', 'delete', 'dense_rank', 108 | 'deref', 'describe', 'deterministic', 'disallow', 'disconnect', 'distinct', 'double', 'drop', 109 | 'dynamic', 'each', 'element', 'else', 'empty', 'end', 'end-exec', 'end_frame', 'end_partition', 110 | 'equals', 'escape', 'every', 'except', 'exec', 'execute', 'exists', 'exp', 'explain', 'extend', 111 | 'external', 'extract', 'false', 'fetch', 'filter', 'first_value', 'float', 'floor', 'for', 112 | 'foreign', 'frame_row', 'free', 'from', 'full', 'function', 'fusion', 'get', 'global', 'grant', 113 | 'group', 'grouping', 'groups', 'having', 'hold', 'hour', 'identity', 'import', 'in', 114 | 'indicator', 'initial', 'inner', 'inout', 'insensitive', 'insert', 'int', 'integer', 115 | 'intersect', 'intersection', 'interval', 'into', 'is', 'join', 'lag', 'language', 'large', 116 | 'last_value', 'lateral', 'lead', 'leading', 'left', 'like', 'like_regex', 'limit', 'ln', 117 | 'local', 'localtime', 'localtimestamp', 'lower', 'match', 'matches', 'match_number', 118 | 'match_recognize', 'max', 'measures', 'member', 'merge', 'method', 'min', 'minute', 'mod', 119 | 'modifies', 'module', 'month', 'more', 'multiset', 'national', 'natural', 'nchar', 'nclob', 120 | 'new', 'next', 'no', 'none', 'normalize', 'not', 'nth_value', 'ntile', 'null', 'nullif', 121 | 'numeric', 'occurrences_regex', 'octet_length', 'of', 'offset', 'old', 'omit', 'on', 'one', 122 | 'only', 'open', 'or', 'order', 'out', 'outer', 'over', 'overlaps', 'overlay', 'parameter', 123 | 'partition', 'pattern', 'per', 'percent', 'percentile_cont', 'percentile_disc', 'percent_rank', 124 | 'period', 'permute', 'portion', 'position', 'position_regex', 'power', 'precedes', 'precision', 125 | 'prepare', 'prev', 'primary', 'procedure', 'range', 'rank', 'reads', 'real', 'recursive', 126 | 'ref', 'references', 'referencing', 'regr_avgx', 'regr_avgy', 'regr_count', 'regr_intercept', 127 | 'regr_r2', 'regr_slope', 'regr_sxx', 'regr_sxy', 'regr_syy', 'release', 'reset', 'result', 128 | 'return', 'returns', 'revoke', 'right', 'rollback', 'rollup', 'row', 'row_number', 'rows', 129 | 'running', 'savepoint', 'scope', 'scroll', 'search', 'second', 'seek', 'select', 'sensitive', 130 | 'session_user', 'set', 'minus', 'show', 'similar', 'skip', 'smallint', 'some', 'specific', 131 | 'specifictype', 'sql', 'sqlexception', 'sqlstate', 'sqlwarning', 'sqrt', 'start', 'static', 132 | 'stddev_pop', 'stddev_samp', 'stream', 'submultiset', 'subset', 'substring', 'substring_regex', 133 | 'succeeds', 'sum', 'symmetric', 'system', 'system_time', 'system_user', 'table', 'tablesample', 134 | 'then', 'time', 'timestamp', 'timezone_hour', 'timezone_minute', 'tinyint', 'to', 'trailing', 135 | 'translate', 'translate_regex', 'translation', 'treat', 'trigger', 'trim', 'trim_array', 136 | 'true', 'truncate', 'uescape', 'union', 'unique', 'unknown', 'unnest', 'update', 'upper', 137 | 'upsert', 'user', 'using', 'value', 'values', 'value_of', 'var_pop', 'var_samp', 'varbinary', 138 | 'varchar', 'varying', 'versioning', 'when', 'whenever', 'where', 'width_bucket', 'window', 139 | 'with', 'within', 'without', 'year'} 140 | 141 | dremio_unique = dremio_reserved - reserved_words 142 | reserved_words.update(list(dremio_unique)) 143 | 144 | def __init__(self, dialect): 145 | super(DremioIdentifierPreparer, self). \ 146 | __init__(dialect, initial_quote='"', final_quote='"') 147 | 148 | 149 | class DremioDialect(default.DefaultDialect): 150 | name = _dialect_name 151 | driver = _dialect_name 152 | supports_sane_rowcount = False 153 | supports_sane_multi_rowcount = False 154 | poolclass = pool.SingletonThreadPool 155 | statement_compiler = DremioCompiler 156 | ddl_compiler = DremioDDLCompiler 157 | preparer = DremioIdentifierPreparer 158 | execution_ctx_cls = DremioExecutionContext 159 | default_paramstyle = "qmark" 160 | filter_schema_names = [] 161 | 162 | @classmethod 163 | def dbapi(cls): 164 | import pyodbc as module 165 | return module 166 | 167 | def connect(self, *cargs, **cparams): 168 | engine_params = [param.lower() for param in cparams.keys()] 169 | if 'autocommit' not in engine_params: 170 | cparams['autocommit'] = 1 171 | 172 | return self.dbapi.connect(*cargs, **cparams) 173 | 174 | def last_inserted_ids(self): 175 | return self.context.last_inserted_ids 176 | 177 | def get_indexes(self, connection, table_name, schema, **kw): 178 | return [] 179 | 180 | def get_pk_constraint(self, connection, table_name, schema=None, **kw): 181 | return [] 182 | 183 | def get_foreign_keys(self, connection, table_name, schema=None, **kw): 184 | return [] 185 | 186 | def get_columns(self, connection, table_name, schema, **kw): 187 | sql = "DESCRIBE \"{0}\"".format(table_name) 188 | if schema is not None and schema != "": 189 | sql = "DESCRIBE \"{0}\".\"{1}\"".format(schema, table_name) 190 | cursor = connection.execute(sql) 191 | result = [] 192 | for col in cursor: 193 | cname = col[0] 194 | ctype = _type_map[col[1]] 195 | column = { 196 | "name": cname, 197 | "type": ctype, 198 | "default": None, 199 | "comment": None, 200 | "nullable": True 201 | } 202 | result.append(column) 203 | return (result) 204 | 205 | @reflection.cache 206 | def get_table_names(self, connection, schema, **kw): 207 | sql = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA."TABLES"' 208 | 209 | # Reverting #5 as Dremio does not support parameterized queries. 210 | if schema is not None: 211 | sql += " WHERE TABLE_SCHEMA = '" + schema + "'" 212 | 213 | result = connection.execute(sql) 214 | table_names = [r[0] for r in result] 215 | return table_names 216 | 217 | def get_schema_names(self, connection, schema=None, **kw): 218 | if len(self.filter_schema_names) > 0: 219 | return self.filter_schema_names 220 | 221 | result = connection.execute("SHOW SCHEMAS") 222 | schema_names = [r[0] for r in result] 223 | return schema_names 224 | 225 | @reflection.cache 226 | def has_table(self, connection, table_name, schema=None, **kw): 227 | sql = 'SELECT COUNT(*) FROM INFORMATION_SCHEMA."TABLES"' 228 | sql += " WHERE TABLE_NAME = '" + str(table_name) + "'" 229 | if schema is not None and schema != "": 230 | sql += " AND TABLE_SCHEMA = '" + str(schema) + "'" 231 | result = connection.execute(sql) 232 | countRows = [r[0] for r in result] 233 | return countRows[0] > 0 234 | 235 | def get_view_names(self, connection, schema=None, **kwargs): 236 | return [] 237 | 238 | # Workaround since Dremio does not support parameterized stmts 239 | # Old queries should not have used queries with parameters, since Dremio does not support it 240 | # and these queries failed. If there is no parameter, everything should work as before. 241 | def do_execute(self, cursor, statement, parameters, context): 242 | replaced_stmt = statement 243 | for v in parameters: 244 | escaped_str = str(v).replace("'", "''") 245 | if isinstance(v, (int, float)): 246 | replaced_stmt = replaced_stmt.replace('?', escaped_str, 1) 247 | else: 248 | replaced_stmt = replaced_stmt.replace('?', "'" + escaped_str + "'", 1) 249 | 250 | super(DremioDialect, self).do_execute_no_params( 251 | cursor, replaced_stmt, context 252 | ) 253 | -------------------------------------------------------------------------------- /sqlalchemy_dremio/flight.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import schema, types, pool 2 | from sqlalchemy.engine import default, reflection 3 | from sqlalchemy.sql import compiler 4 | 5 | _dialect_name = "dremio+flight" 6 | 7 | _type_map = { 8 | 'boolean': types.BOOLEAN, 9 | 'BOOLEAN': types.BOOLEAN, 10 | 'varbinary': types.LargeBinary, 11 | 'VARBINARY': types.LargeBinary, 12 | 'date': types.DATE, 13 | 'DATE': types.DATE, 14 | 'float': types.FLOAT, 15 | 'FLOAT': types.FLOAT, 16 | 'decimal': types.DECIMAL, 17 | 'DECIMAL': types.DECIMAL, 18 | 'double': types.FLOAT, 19 | 'DOUBLE': types.FLOAT, 20 | 'interval': types.Interval, 21 | 'INTERVAL': types.Interval, 22 | 'int': types.INTEGER, 23 | 'INT': types.INTEGER, 24 | 'integer': types.INTEGER, 25 | 'INTEGER': types.INTEGER, 26 | 'bigint': types.BIGINT, 27 | 'BIGINT': types.BIGINT, 28 | 'time': types.TIME, 29 | 'TIME': types.TIME, 30 | 'timestamp': types.TIMESTAMP, 31 | 'TIMESTAMP': types.TIMESTAMP, 32 | 'varchar': types.VARCHAR, 33 | 'VARCHAR': types.VARCHAR, 34 | 'smallint': types.SMALLINT, 35 | 'CHARACTER VARYING': types.VARCHAR, 36 | 'ANY': types.VARCHAR 37 | } 38 | 39 | 40 | class DremioExecutionContext(default.DefaultExecutionContext): 41 | pass 42 | 43 | 44 | class DremioCompiler(compiler.SQLCompiler): 45 | def visit_char_length_func(self, fn, **kw): 46 | return 'length{}'.format(self.function_argspec(fn, **kw)) 47 | 48 | def visit_table(self, table, asfrom=False, **kwargs): 49 | 50 | if asfrom: 51 | if table.schema is not None and table.schema != "": 52 | fixed_schema = ".".join(["\"" + i.replace('"', '') + "\"" for i in table.schema.split(".")]) 53 | fixed_table = fixed_schema + ".\"" + table.name.replace("\"", "") + "\"" 54 | else: 55 | fixed_table = "\"" + table.name.replace("\"", "") + "\"" 56 | return fixed_table 57 | else: 58 | return "" 59 | 60 | def visit_tablesample(self, tablesample, asfrom=False, **kw): 61 | print(tablesample) 62 | 63 | 64 | class DremioDDLCompiler(compiler.DDLCompiler): 65 | def get_column_specification(self, column, **kwargs): 66 | colspec = self.preparer.format_column(column) 67 | colspec += " " + self.dialect.type_compiler.process(column.type) 68 | if column is column.table._autoincrement_column and \ 69 | True and \ 70 | ( 71 | column.default is None or \ 72 | isinstance(column.default, schema.Sequence) 73 | ): 74 | colspec += " IDENTITY" 75 | if isinstance(column.default, schema.Sequence) and \ 76 | column.default.start > 0: 77 | colspec += " " + str(column.default.start) 78 | else: 79 | default = self.get_column_default_string(column) 80 | if default is not None: 81 | colspec += " DEFAULT " + default 82 | 83 | if not column.nullable: 84 | colspec += " NOT NULL" 85 | return colspec 86 | 87 | 88 | class DremioIdentifierPreparer(compiler.IdentifierPreparer): 89 | reserved_words = compiler.RESERVED_WORDS.copy() 90 | dremio_reserved = {'abs', 'all', 'allocate', 'allow', 'alter', 'and', 'any', 'are', 'array', 91 | 'array_max_cardinality', 'as', 'asensitivelo', 'asymmetric', 'at', 'atomic', 'authorization', 92 | 'avg', 'begin', 'begin_frame', 'begin_partition', 'between', 'bigint', 'binary', 'bit', 'blob', 93 | 'boolean', 'both', 'by', 'call', 'called', 'cardinality', 'cascaded', 'case', 'cast', 'ceil', 94 | 'ceiling', 'char', 'char_length', 'character', 'character_length', 'check', 'classifier', 95 | 'clob', 'close', 'coalesce', 'collate', 'collect', 'column', 'commit', 'condition', 'connect', 96 | 'constraint', 'contains', 'convert', 'corr', 'corresponding', 'count', 'covar_pop', 97 | 'covar_samp', 'create', 'cross', 'cube', 'cume_dist', 'current', 'current_catalog', 98 | 'current_date', 'current_default_transform_group', 'current_path', 'current_role', 99 | 'current_row', 'current_schema', 'current_time', 'current_timestamp', 100 | 'current_transform_group_for_type', 'current_user', 'cursor', 'cycle', 'date', 'day', 101 | 'deallocate', 'dec', 'decimal', 'declare', 'default', 'define', 'delete', 'dense_rank', 102 | 'deref', 'describe', 'deterministic', 'disallow', 'disconnect', 'distinct', 'double', 'drop', 103 | 'dynamic', 'each', 'element', 'else', 'empty', 'end', 'end-exec', 'end_frame', 'end_partition', 104 | 'equals', 'escape', 'every', 'except', 'exec', 'execute', 'exists', 'exp', 'explain', 'extend', 105 | 'external', 'extract', 'false', 'fetch', 'filter', 'first_value', 'float', 'floor', 'for', 106 | 'foreign', 'frame_row', 'free', 'from', 'full', 'function', 'fusion', 'get', 'global', 'grant', 107 | 'group', 'grouping', 'groups', 'having', 'hold', 'hour', 'identity', 'import', 'in', 108 | 'indicator', 'initial', 'inner', 'inout', 'insensitive', 'insert', 'int', 'integer', 109 | 'intersect', 'intersection', 'interval', 'into', 'is', 'join', 'lag', 'language', 'large', 110 | 'last_value', 'lateral', 'lead', 'leading', 'left', 'like', 'like_regex', 'limit', 'ln', 111 | 'local', 'localtime', 'localtimestamp', 'lower', 'match', 'matches', 'match_number', 112 | 'match_recognize', 'max', 'measures', 'member', 'merge', 'method', 'min', 'minute', 'mod', 113 | 'modifies', 'module', 'month', 'more', 'multiset', 'national', 'natural', 'nchar', 'nclob', 114 | 'new', 'next', 'no', 'none', 'normalize', 'not', 'nth_value', 'ntile', 'null', 'nullif', 115 | 'numeric', 'occurrences_regex', 'octet_length', 'of', 'offset', 'old', 'omit', 'on', 'one', 116 | 'only', 'open', 'or', 'order', 'out', 'outer', 'over', 'overlaps', 'overlay', 'parameter', 117 | 'partition', 'pattern', 'per', 'percent', 'percentile_cont', 'percentile_disc', 'percent_rank', 118 | 'period', 'permute', 'portion', 'position', 'position_regex', 'power', 'precedes', 'precision', 119 | 'prepare', 'prev', 'primary', 'procedure', 'range', 'rank', 'reads', 'real', 'recursive', 120 | 'ref', 'references', 'referencing', 'regr_avgx', 'regr_avgy', 'regr_count', 'regr_intercept', 121 | 'regr_r2', 'regr_slope', 'regr_sxx', 'regr_sxy', 'regr_syy', 'release', 'reset', 'result', 122 | 'return', 'returns', 'revoke', 'right', 'rollback', 'rollup', 'row', 'row_number', 'rows', 123 | 'running', 'savepoint', 'scope', 'scroll', 'search', 'second', 'seek', 'select', 'sensitive', 124 | 'session_user', 'set', 'minus', 'show', 'similar', 'skip', 'smallint', 'some', 'specific', 125 | 'specifictype', 'sql', 'sqlexception', 'sqlstate', 'sqlwarning', 'sqrt', 'start', 'static', 126 | 'stddev_pop', 'stddev_samp', 'stream', 'submultiset', 'subset', 'substring', 'substring_regex', 127 | 'succeeds', 'sum', 'symmetric', 'system', 'system_time', 'system_user', 'table', 'tablesample', 128 | 'then', 'time', 'timestamp', 'timezone_hour', 'timezone_minute', 'tinyint', 'to', 'trailing', 129 | 'translate', 'translate_regex', 'translation', 'treat', 'trigger', 'trim', 'trim_array', 130 | 'true', 'truncate', 'uescape', 'union', 'unique', 'unknown', 'unnest', 'update', 'upper', 131 | 'upsert', 'user', 'using', 'value', 'values', 'value_of', 'var_pop', 'var_samp', 'varbinary', 132 | 'varchar', 'varying', 'versioning', 'when', 'whenever', 'where', 'width_bucket', 'window', 133 | 'with', 'within', 'without', 'year'} 134 | 135 | dremio_unique = dremio_reserved - reserved_words 136 | reserved_words.update(list(dremio_unique)) 137 | 138 | def __init__(self, dialect): 139 | super(DremioIdentifierPreparer, self). \ 140 | __init__(dialect, initial_quote='"', final_quote='"') 141 | 142 | 143 | class DremioExecutionContext_flight(DremioExecutionContext): 144 | pass 145 | 146 | 147 | class DremioDialect_flight(default.DefaultDialect): 148 | 149 | name = _dialect_name 150 | driver = _dialect_name 151 | supports_sane_rowcount = False 152 | supports_sane_multi_rowcount = False 153 | poolclass = pool.SingletonThreadPool 154 | statement_compiler = DremioCompiler 155 | paramstyle = 'pyformat' 156 | ddl_compiler = DremioDDLCompiler 157 | preparer = DremioIdentifierPreparer 158 | execution_ctx_cls = DremioExecutionContext 159 | 160 | def create_connect_args(self, url): 161 | opts = url.translate_connect_args(username='user') 162 | connect_args = {} 163 | connectors = ['HOST=%s' % opts['host'], 164 | 'PORT=%s' % opts['port']] 165 | 166 | if 'user' in opts: 167 | connectors.append('{0}={1}'.format('UID', opts['user'])) 168 | connectors.append('{0}={1}'.format('PWD', opts['password'])) 169 | 170 | if 'database' in opts: 171 | connectors.append('{0}={1}'.format('Schema', opts['database'])) 172 | 173 | # Clone the query dictionary with lower-case keys. 174 | lc_query_dict = {k.lower(): v for k, v in url.query.items()} 175 | 176 | def add_property(lc_query_dict, property_name, connectors): 177 | if property_name.lower() in lc_query_dict: 178 | connectors.append('{0}={1}'.format(property_name, lc_query_dict[property_name.lower()])) 179 | 180 | add_property(lc_query_dict, 'UseEncryption', connectors) 181 | add_property(lc_query_dict, 'DisableCertificateVerification', connectors) 182 | add_property(lc_query_dict, 'TrustedCerts', connectors) 183 | add_property(lc_query_dict, 'routing_queue', connectors) 184 | add_property(lc_query_dict, 'routing_tag', connectors) 185 | add_property(lc_query_dict, 'quoting', connectors) 186 | add_property(lc_query_dict, 'routing_engine', connectors) 187 | add_property(lc_query_dict, 'Token', connectors) 188 | 189 | return [[";".join(connectors)], connect_args] 190 | 191 | @classmethod 192 | def dbapi(cls): 193 | import sqlalchemy_dremio.db as module 194 | return module 195 | 196 | def connect(self, *cargs, **cparams): 197 | return self.dbapi.connect(*cargs, **cparams) 198 | 199 | def last_inserted_ids(self): 200 | return self.context.last_inserted_ids 201 | 202 | def get_indexes(self, connection, table_name, schema, **kw): 203 | return [] 204 | 205 | def get_pk_constraint(self, connection, table_name, schema=None, **kw): 206 | return [] 207 | 208 | def get_foreign_keys(self, connection, table_name, schema=None, **kw): 209 | return [] 210 | 211 | def get_columns(self, connection, table_name, schema, **kw): 212 | sql = "DESCRIBE \"{0}\"".format(table_name) 213 | if schema is not None and schema != "": 214 | sql = "DESCRIBE \"{0}\".\"{1}\"".format(schema, table_name) 215 | cursor = connection.execute(sql) 216 | result = [] 217 | for col in cursor: 218 | cname = col[0] 219 | ctype = _type_map[col[1]] 220 | column = { 221 | "name": cname, 222 | "type": ctype, 223 | "default": None, 224 | "comment": None, 225 | "nullable": True 226 | } 227 | result.append(column) 228 | return (result) 229 | 230 | @reflection.cache 231 | def get_table_names(self, connection, schema, **kw): 232 | sql = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA."TABLES"' 233 | if schema is not None: 234 | sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.\"TABLES\" WHERE TABLE_SCHEMA = '" + schema + "'" 235 | 236 | result = connection.execute(sql) 237 | table_names = [r[0] for r in result] 238 | return table_names 239 | 240 | def get_schema_names(self, connection, schema=None, **kw): 241 | result = connection.execute("SHOW SCHEMAS") 242 | schema_names = [r[0] for r in result] 243 | return schema_names 244 | 245 | 246 | @reflection.cache 247 | def has_table(self, connection, table_name, schema=None, **kw): 248 | sql = 'SELECT COUNT(*) FROM INFORMATION_SCHEMA."TABLES"' 249 | sql += " WHERE TABLE_NAME = '" + str(table_name) + "'" 250 | if schema is not None and schema != "": 251 | sql += " AND TABLE_SCHEMA = '" + str(schema) + "'" 252 | result = connection.execute(sql) 253 | countRows = [r[0] for r in result] 254 | return countRows[0] > 0 255 | 256 | def get_view_names(self, connection, schema=None, **kwargs): 257 | return [] 258 | --------------------------------------------------------------------------------