Skip to content

Commit 2d60846

Browse files
authored
Basic compatibility with Drill < 1.19 for drill+sadrill (#71)
* Add CHANGELOG with note about drill+sadrill and Drill < 1.19. * Basic compat with Drill < 1.19 for drill+sadrill.
1 parent e67dde1 commit 2d60846

File tree

5 files changed

+149
-83
lines changed

5 files changed

+149
-83
lines changed

CHANGELOG.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
## [Unreleased]
2+
3+
## [1.1.1] - 2021-07-28
4+
5+
### Fixed
6+
7+
- Backwards compatibility with Drill < 1.19, limited to returning
8+
all data values as strings. Users not able to upgrade to >= 1.19
9+
must implement their own typecasting or use sqlalchemy-drill 0.3.
10+
11+
## [1.1.0] - 2021-07-21
12+
13+
**N.B.**: The drill+sadrill dialect in this release is not compatible with Drill
14+
< 1.19.
15+
16+
### Changed
17+
18+
- Rewrite the drill+sadrill dialect using the ijson streaming parser.

README.md

Lines changed: 54 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
11
# Apache Drill dialect for SQLAlchemy.
2+
23
---
4+
35
The primary purpose of this is to have a working dialect for Apache Drill that can be used with Apache Superset.
46

57
https://superset.incubator.apache.org
68

7-
Obviously, a working, robust dialect for Drill serves other purposes as well, but most of the iterative planning for this REPO will be based on working with Superset. Other changes will gladly be incorporated, as long as it doesn't hurt Superset integration.
9+
Obviously, a working, robust dialect for Drill serves other purposes as well, but most of the iterative planning for this REPO will be based on working with Superset. Other changes will gladly be incorporated, as long as it doesn't hurt Superset integration.
810

9-
## Installation
10-
Installing the dialect is straightforward. Simply:
11+
## Installation
12+
13+
Installing the dialect is straightforward. Simply:
1114

1215
```
1316
pip install sqlalchemy-drill
@@ -20,28 +23,48 @@ python3 -m pip install git+https://github.com/JohnOmernik/sqlalchemy-drill.git
2023
```
2124

2225
## Usage
26+
2327
To use Drill with SQLAlchemy you will need to craft a connection string in the format below:
2428

2529
```
2630
drill+sadrill://<username>:<password>@<host>:<port>/<storage_plugin>?use_ssl=True
2731
```
2832

29-
To connect to Drill running on a local machine running in embedded mode you can use the following connection string.
33+
To connect to Drill running on a local machine running in embedded mode you can use the following connection string.
34+
3035
```
3136
drill+sadrill://localhost:8047/dfs?use_ssl=False
3237
```
3338

39+
Query result metadata returned by the Drill REST API is stored in the `result_md` field of the DB-API Cursor object. Note that any trailing metadata, i.e. metadata which comes after result row data, will only be populated after you have iterated through all of the returned rows. If you need this trailing metadata you can make the cursor object reachable after it has been completely iterated by obtaining a reference to it beforehand, as follows.
40+
```python
41+
r = engine.execute('select current_timestamp')
42+
r.cursor.result_md # access metadata, but only leading metadata
43+
cur = r.cursor # obtain a reference for use later
44+
r.fetchall() # iterate through all result data
45+
cur.result_md # access metadata, including trailing metadata
46+
del cur # optionally delete the reference when done
47+
```
48+
49+
### Changes in Drill 1.19 affecting drill+sadrill
50+
51+
In versions of Drill earlier than 1.19, all data values are serialised to JSON strings and column type metadata comes after the data itself. As a result, for these versions of Drill, the drill+sadrill dialect returns every data value as a string. To convert non-string data to its native type you need to typecast it yourself.
52+
53+
In Drill 1.19 the REST API began making use of numeric types in JSON for numbers and times, the latter via a UNIX time representation. As a result, the drill+sadrill dialect is able to return appropriate types for numbers and times when used with Drill >= 1.19.
54+
3455
## Usage with JDBC
56+
3557
Connecting to Drill via JDBC is a little more complicated than a local installation and complete instructions can be found on the Drill documentation here: https://drill.apache.org/docs/using-the-jdbc-driver/.
3658

3759
In order to configure SQLAlchemy to work with Drill via JDBC you must:
38-
* Download the latest JDBC Driver available here: http://apache.osuosl.org/drill/
39-
* Copy this driver to your classpath or other known path
40-
* Set an environment variable called `DRILL_JDBC_DRIVER_PATH` to the full path of your driver location
41-
* Set an environment variable called `DRILL_JDBC_JAR_NAME` to the name of the `.jar` file for the Drill driver.
4260

43-
Additionally, you will need to install `JayDeBeApi` as well as jPype version 0.6.3.
44-
These modules are listed as optional dependencies and will not be installed by the default installer.
61+
- Download the latest JDBC Driver available here: http://apache.osuosl.org/drill/
62+
- Copy this driver to your classpath or other known path
63+
- Set an environment variable called `DRILL_JDBC_DRIVER_PATH` to the full path of your driver location
64+
- Set an environment variable called `DRILL_JDBC_JAR_NAME` to the name of the `.jar` file for the Drill driver.
65+
66+
Additionally, you will need to install `JayDeBeApi` as well as jPype version 0.6.3.
67+
These modules are listed as optional dependencies and will not be installed by the default installer.
4568

4669
If the JDBC driver is not available, the dialect will throw errors when trying
4770
to connect. In addition, sqlalchemy-drill will not launch a JVM for you so you
@@ -55,52 +78,62 @@ jpype.startJVM("-ea", classpath="lib/*")
5578
```
5679
drill+jdbc://<username>:<passsword>@<host>:<port>
5780
```
81+
5882
For a simple installation, this might look like:
83+
5984
```
6085
drill+jdbc://admin:password@localhost:31010
6186
```
6287

6388
## Usage with ODBC
89+
6490
In order to configure SQLAlchemy to work with Drill via ODBC you must:
65-
* Install latest Drill ODBC Driver: https://drill.apache.org/docs/installing-the-driver-on-linux/
66-
* Ensure that you have ODBC support in your system (`unixODBC` package for RedHat-based systems).
67-
* Install `pyodbc` Python package.
68-
This module is listed as an optional dependency and will not be installed by the default installer.
91+
92+
- Install latest Drill ODBC Driver: https://drill.apache.org/docs/installing-the-driver-on-linux/
93+
- Ensure that you have ODBC support in your system (`unixODBC` package for RedHat-based systems).
94+
- Install `pyodbc` Python package.
95+
This module is listed as an optional dependency and will not be installed by the default installer.
6996

7097
To connect to Drill with SQLAlchemy use the following connection string:
98+
7199
```
72100
drill+odbc:///?<ODBC connection parameters>
73101
```
74102

75103
Connection properties are available in the official documentation: https://drill.apache.org/docs/odbc-configuration-reference/
76104

77105
For a simple installation, this might look like:
106+
78107
```
79108
drill+odbc:///?Driver=/opt/mapr/drill/lib/64/libdrillodbc_sb64.so&ConnectionType=Direct&HOST=localhost&PORT=31010&AuthenticationType=Plain&UID=admin&PWD=password
80109
```
110+
81111
or for the case when you have DSN configured in `odbc.ini`:
112+
82113
```
83114
drill+odbc:///?DSN=drill_dsn_name
84115
```
85116

86117
**Note:** it's better to avoid using connection string with `hostname:port` or `username`/`password`, like 'drill+odbc://admin:password@localhost:31010/' but use only ODBC properties instead to avoid any misinterpretation between these parameters.
87118

88-
89119
## Usage with Superset
90-
For a complete tutorial on how to use Superset with Drill, read the tutorial on @cgivre's blog available here: http://thedataist.com/visualize-anything-with-superset-and-drill/.
91120

121+
For a complete tutorial on how to use Superset with Drill, read the tutorial on @cgivre's blog available here: http://thedataist.com/visualize-anything-with-superset-and-drill/.
92122

93123
## Current Status/Development Approach
124+
94125
Currently we can connect to drill, and issue queries for most visualizations and get results. We also enumerate table columns for some times of tables. Here are things that are working as some larger issues to work out. (Individual issues are tracked under issues)
95126

96-
* Connection to Drill via the databases tab in Superset succeeds
97-
* You can do basic queries for most types of viz/tables
98-
* There may be issues with advanced queries/joins. As you learn about new ones, please track in issues
127+
- Connection to Drill via the databases tab in Superset succeeds
128+
- You can do basic queries for most types of viz/tables
129+
- There may be issues with advanced queries/joins. As you learn about new ones, please track in issues
99130

100131
### Many thanks
101-
to drillpy and pydrill for code used in creating the `drilldbapi.py` code for connecting!
102132

103-
### Docker
133+
to drillpy and pydrill for code used in creating the original `drilldbapi.py` code for connecting!
134+
135+
### Docker
136+
104137
It is recommended to extend [the official Docker image](https://hub.docker.com/r/apache/superset) to include this Apache Drill driver:
105138

106139
```dockerfile

setup.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
long_description = f.read()
3030

3131
setup(name='sqlalchemy_drill',
32-
version='1.1.0',
32+
version='1.1.1',
3333
description="Apache Drill for SQLAlchemy",
3434
long_description=long_description,
3535
long_description_content_type="text/markdown",
@@ -64,7 +64,7 @@
6464
license='MIT',
6565
url='https://github.com/JohnOmernik/sqlalchemy-drill',
6666
download_url='https://github.com/JohnOmernik/sqlalchemy-drill/archive/'
67-
'1.1.0.tar.gz',
67+
'1.1.1.tar.gz',
6868
packages=find_packages(),
6969
include_package_data=True,
7070
tests_require=['nose >= 0.11'],

sqlalchemy_drill/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
2020
# DEALINGS IN THE SOFTWARE.
2121

22-
__version__ = '1.1.0'
22+
__version__ = '1.1.1'
2323
from sqlalchemy.dialects import registry
2424

2525
registry.register("drill", "sqlalchemy_drill.sadrill", "DrillDialect_sadrill")

sqlalchemy_drill/drilldbapi/_drilldbapi.py

Lines changed: 74 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def __init__(self, conn):
5555

5656
self._is_open: bool = True
5757
self._result_event_stream = self._row_stream = None
58-
self._typecasters: list = None
58+
self._typecaster_list: list = None
5959

6060
def is_open(func):
6161
'''Decorator for methods which require a connection'''
@@ -74,9 +74,19 @@ def func_wrapper(self, *args, **kwargs):
7474

7575
return func_wrapper
7676

77-
def _typecast(self, row) -> tuple:
78-
'''Internal method to cast REST API values to Python types'''
79-
return tuple((f(v) for f, v in zip(self._typecasters, row)))
77+
def _gen_description(self, col_types):
78+
blank = [None] * len(self.result_md['columns'])
79+
self.description = tuple(
80+
zip(
81+
self.result_md['columns'], # name
82+
col_types or blank, # type_code
83+
blank, # display_size
84+
blank, # internal_size
85+
blank, # precision
86+
blank, # scale
87+
blank # null_ok
88+
)
89+
)
8090

8191
def _report_query_state(self):
8292
md = self.result_md
@@ -187,33 +197,36 @@ def execute(self, operation, parameters=()):
187197

188198
self._result_event_stream = parse(RequestsStreamWrapper(resp))
189199
row_data_present = self._outer_parsing_loop()
200+
# The leading result metadata has now been parsed.
190201

191-
# The leading, and possibly all, result metadata has now been parsed.
192-
md = self.result_md
193-
logger.info(f'received Drill query ID {md.get("queryId", None)}.')
202+
logger.info(
203+
f'received Drill query ID {self.result_md.get("queryId", None)}.'
204+
)
194205

195-
if row_data_present:
196-
# strip size information in column types e.g. in VARCHAR(10)
197-
coltypes = list(
198-
map(lambda m: re.sub(r'\(.*\)', '', m), md.pop('metadata'))
199-
)
200-
ncols = len(coltypes)
201-
202-
md['column_types'] = coltypes
203-
self._typecasters = [TYPECASTERS.get(
204-
m, lambda v: v) for m in coltypes]
205-
self.description = tuple(
206-
zip(
207-
md['columns'], # name
208-
md['column_types'], # type_code
209-
[None] * ncols, # display_size
210-
[None] * ncols, # internal_size
211-
[None] * ncols, # precision
212-
[None] * ncols, # scale
213-
[None] * ncols # null_ok
214-
)
206+
if not row_data_present:
207+
return
208+
209+
cols = self.result_md['columns']
210+
# Column metadata could be trailing or entirely absent
211+
if 'metadata' in self.result_md:
212+
md = self.result_md['metadata']
213+
# strip size information from column types e.g. VARCHAR(10)
214+
basic_coltypes = [re.sub(r'\(.*\)', '', m) for m in md]
215+
self._gen_description(basic_coltypes)
216+
217+
self._typecaster_list = [
218+
self.connection.typecasters.get(col, lambda v: v) for
219+
col in basic_coltypes
220+
]
221+
else:
222+
self._gen_description(None)
223+
logger.warn(
224+
'encountered data before metadata, typecasting during '
225+
'streaming by this module will not take place. Upgrade '
226+
'to Drill >= 1.19 or apply your own typecasting.'
215227
)
216-
logger.info(f'opened a row data stream of {ncols} columns.')
228+
229+
logger.info(f'opened a row data stream of {len(cols)} columns.')
217230

218231
@is_open
219232
def executemany(self, operation, seq_of_parameters):
@@ -246,8 +259,14 @@ def fetchmany(self, size: int = None):
246259

247260
try:
248261
while self.rownumber != fetch_until:
249-
row = self._typecast(tuple(next(self._row_stream).values()))
250-
results.append(row)
262+
row_dict = next(self._row_stream)
263+
# values ordered according to self.result_md['columns']
264+
row = [row_dict[col] for col in self.result_md['columns']]
265+
266+
if self._typecaster_list is not None:
267+
row = (f(v) for f, v in zip(self._typecaster_list, row))
268+
269+
results.append(tuple(row))
251270
self.rownumber += 1
252271

253272
if self.rownumber % api_globals._PROGRESS_LOG_N == 0:
@@ -310,22 +329,37 @@ def __iter__(self):
310329
class Connection(object):
311330
def __init__(self,
312331
host: str,
313-
db: str,
314332
port: int,
315333
proto: str,
316334
session: Session):
317335
if session is None:
318336
raise ProgrammingError('A Requests session is required.', None)
319337

320-
self.host = host
321-
self.db = db
322-
self.proto = proto
323-
self.port = port
324338
self._base_url = f'{proto}{host}:{port}'
325339
self._session = session
326340
self._connected = True
327341

328-
def submit_query(self, query):
342+
logger.debug('queries Drill\'s version number...')
343+
resp = self.submit_query(
344+
'select min(version) version from sys.drillbits'
345+
)
346+
self.drill_version = resp.json()['rows'][0]['version']
347+
logger.info(f'has connected to Drill version {self.drill_version}.')
348+
349+
if self.drill_version < '1.19':
350+
self.typecasters = {}
351+
else:
352+
# Starting in 1.19 the Drill REST API returns UNIX times
353+
self.typecasters = {
354+
'DATE': lambda v: DateFromTicks(v/1000),
355+
'TIME': lambda v: TimeFromTicks(v/1000),
356+
'TIMESTAMP': lambda v: TimestampFromTicks(v/1000)
357+
}
358+
logger.debug(
359+
'sets up typecasting functions for Drill >= 1.19.'
360+
)
361+
362+
def submit_query(self, query: str):
329363
payload = api_globals._PAYLOAD.copy()
330364
# TODO: autoLimit, defaultSchema
331365
payload['query'] = query
@@ -342,6 +376,7 @@ def submit_query(self, query):
342376
)
343377

344378
# Decorator for methods which require connection
379+
345380
def connected(func):
346381

347382
def func_wrapper(self, *args, **kwargs):
@@ -429,25 +464,11 @@ def connect(host: str,
429464
logger.error('failed to authenticate to Drill.')
430465
raise AuthError(str(raw_data), response.status_code)
431466

467+
conn = Connection(host, port, proto, session)
432468
if db is not None:
433-
payload = api_globals._PAYLOAD.copy()
434-
payload['query'] = f'USE {db}'
435-
# payload['query'] = "SELECT 'test' FROM (VALUES(1))"
436-
437-
response = session.post(
438-
f'{base_url}/query.json',
439-
data=dumps(payload),
440-
headers=api_globals._HEADER
441-
)
469+
conn.submit_query(f'USE {db}')
442470

443-
if response.status_code != 200:
444-
logger.error(f'received an error when trying to USE {db}')
445-
raise DatabaseError(
446-
str(response.json().get('errorMessage', None)),
447-
response.status_code
448-
)
449-
450-
return Connection(host, db, port, proto, session)
471+
return conn
451472

452473

453474
class RequestsStreamWrapper(object):
@@ -510,12 +531,6 @@ def __cmp__(self, other):
510531
return -1
511532

512533

513-
TYPECASTERS = {
514-
'DATE': lambda v: DateFromTicks(v/1000),
515-
'TIME': lambda v: TimeFromTicks(v/1000),
516-
'TIMESTAMP': lambda v: TimestampFromTicks(v/1000)
517-
}
518-
519534
# Mandatory type objects defined by DB-API 2 specs.
520535

521536
STRING = DBAPITypeObject('VARCHAR')

0 commit comments

Comments
 (0)