forked from databricks/databricks-sql-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnative.py
More file actions
720 lines (569 loc) · 22.5 KB
/
native.py
File metadata and controls
720 lines (569 loc) · 22.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
import datetime
import decimal
from enum import Enum, auto
from typing import Optional, Sequence, Any
from databricks.sql.exc import NotSupportedError
from databricks.sql.thrift_api.TCLIService.ttypes import (
TSparkParameter,
TSparkParameterValue,
TSparkParameterValueArg,
)
import datetime
import decimal
from enum import Enum, auto
from typing import Dict, List, Union
class ParameterApproach(Enum):
INLINE = 1
NATIVE = 2
NONE = 3
class ParameterStructure(Enum):
NAMED = 1
POSITIONAL = 2
NONE = 3
class DatabricksSupportedType(Enum):
"""Enumerate every supported Databricks SQL type shown here:
https://docs.databricks.com/en/sql/language-manual/sql-ref-datatypes.html
"""
BIGINT = auto()
BINARY = auto()
BOOLEAN = auto()
DATE = auto()
DECIMAL = auto()
DOUBLE = auto()
FLOAT = auto()
INT = auto()
INTERVAL = auto()
VOID = auto()
SMALLINT = auto()
STRING = auto()
TIMESTAMP = auto()
TIMESTAMP_NTZ = auto()
TINYINT = auto()
ARRAY = auto()
MAP = auto()
STRUCT = auto()
TAllowedParameterValue = Union[
str,
int,
float,
datetime.datetime,
datetime.date,
bool,
decimal.Decimal,
None,
list,
dict,
tuple,
]
class DbsqlParameterBase:
"""Parent class for IntegerParameter, DecimalParameter etc..
Each each instance that extends this base class should be capable of generating a TSparkParameter
It should know how to generate a cast expression based off its DatabricksSupportedType.
By default the cast expression should render the string value of it's `value` and the literal
name of its Databricks Supported Type
Interface should be:
from databricks.sql.parameters import DecimalParameter
param = DecimalParameter(value, scale=None, precision=None)
cursor.execute("SELECT ?",[param])
Or
from databricks.sql.parameters import IntegerParameter
param = IntegerParameter(42)
cursor.execute("SELECT ?", [param])
"""
CAST_EXPR: str
name: Optional[str]
value: Any
def as_tspark_param(self, named: bool) -> TSparkParameter:
"""Returns a TSparkParameter object that can be passed to the DBR thrift server."""
tsp = TSparkParameter(value=self._tspark_param_value(), type=self._cast_expr())
if named:
tsp.name = self.name
tsp.ordinal = False
elif not named:
tsp.ordinal = True
return tsp
def _tspark_param_value(self):
return TSparkParameterValue(stringValue=str(self.value))
def _tspark_value_arg(self):
"""Returns a TSparkParameterValueArg object that can be passed to the DBR thrift server."""
return TSparkParameterValueArg(value=str(self.value), type=self._cast_expr())
def _cast_expr(self):
return self.CAST_EXPR
def __str__(self):
return f"{self.__class__}(name={self.name}, value={self.value})"
def __repr__(self):
return self.__str__()
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
class IntegerParameter(DbsqlParameterBase):
"""Wrap a Python `int` that will be bound to a Databricks SQL INT column."""
def __init__(self, value: int, name: Optional[str] = None):
"""
:value:
The value to bind for this parameter. This will be casted to an INT.
:name:
If None, your query must contain a `?` marker. Like:
```sql
SELECT * FROM table WHERE field = ?
```
If not None, your query should contain a named parameter marker. Like:
```sql
SELECT * FROM table WHERE field = :my_param
```
The `name` argument to this function would be `my_param`.
"""
self.value = value
self.name = name
CAST_EXPR = DatabricksSupportedType.INT.name
class StringParameter(DbsqlParameterBase):
"""Wrap a Python `str` that will be bound to a Databricks SQL STRING column."""
def __init__(self, value: str, name: Optional[str] = None):
"""
:value:
The value to bind for this parameter. This will be casted to a STRING.
:name:
If None, your query must contain a `?` marker. Like:
```sql
SELECT * FROM table WHERE field = ?
```
If not None, your query should contain a named parameter marker. Like:
```sql
SELECT * FROM table WHERE field = :my_param
```
The `name` argument to this function would be `my_param`.
"""
self.value = value
self.name = name
CAST_EXPR = DatabricksSupportedType.STRING.name
class BigIntegerParameter(DbsqlParameterBase):
"""Wrap a Python `int` that will be bound to a Databricks SQL BIGINT column."""
def __init__(self, value: int, name: Optional[str] = None):
"""
:value:
The value to bind for this parameter. This will be casted to a BIGINT.
:name:
If None, your query must contain a `?` marker. Like:
```sql
SELECT * FROM table WHERE field = ?
```
If not None, your query should contain a named parameter marker. Like:
```sql
SELECT * FROM table WHERE field = :my_param
```
The `name` argument to this function would be `my_param`.
"""
self.value = value
self.name = name
CAST_EXPR = DatabricksSupportedType.BIGINT.name
class BooleanParameter(DbsqlParameterBase):
"""Wrap a Python `bool` that will be bound to a Databricks SQL BOOLEAN column."""
def __init__(self, value: bool, name: Optional[str] = None):
"""
:value:
The value to bind for this parameter. This will be casted to a BOOLEAN.
:name:
If None, your query must contain a `?` marker. Like:
```sql
SELECT * FROM table WHERE field = ?
```
If not None, your query should contain a named parameter marker. Like:
```sql
SELECT * FROM table WHERE field = :my_param
```
The `name` argument to this function would be `my_param`.
"""
self.value = value
self.name = name
CAST_EXPR = DatabricksSupportedType.BOOLEAN.name
class DateParameter(DbsqlParameterBase):
"""Wrap a Python `date` that will be bound to a Databricks SQL DATE column."""
def __init__(self, value: datetime.date, name: Optional[str] = None):
"""
:value:
The value to bind for this parameter. This will be casted to a DATE.
:name:
If None, your query must contain a `?` marker. Like:
```sql
SELECT * FROM table WHERE field = ?
```
If not None, your query should contain a named parameter marker. Like:
```sql
SELECT * FROM table WHERE field = :my_param
```
The `name` argument to this function would be `my_param`.
"""
self.value = value
self.name = name
CAST_EXPR = DatabricksSupportedType.DATE.name
class DoubleParameter(DbsqlParameterBase):
"""Wrap a Python `float` that will be bound to a Databricks SQL DOUBLE column."""
def __init__(self, value: float, name: Optional[str] = None):
"""
:value:
The value to bind for this parameter. This will be casted to a DOUBLE.
:name:
If None, your query must contain a `?` marker. Like:
```sql
SELECT * FROM table WHERE field = ?
```
If not None, your query should contain a named parameter marker. Like:
```sql
SELECT * FROM table WHERE field = :my_param
```
The `name` argument to this function would be `my_param`.
"""
self.value = value
self.name = name
CAST_EXPR = DatabricksSupportedType.DOUBLE.name
class FloatParameter(DbsqlParameterBase):
"""Wrap a Python `float` that will be bound to a Databricks SQL FLOAT column."""
def __init__(self, value: float, name: Optional[str] = None):
"""
:value:
The value to bind for this parameter. This will be casted to a FLOAT.
:name:
If None, your query must contain a `?` marker. Like:
```sql
SELECT * FROM table WHERE field = ?
```
If not None, your query should contain a named parameter marker. Like:
```sql
SELECT * FROM table WHERE field = :my_param
```
The `name` argument to this function would be `my_param`.
"""
self.value = value
self.name = name
CAST_EXPR = DatabricksSupportedType.FLOAT.name
class VoidParameter(DbsqlParameterBase):
"""Wrap a Python `None` that will be bound to a Databricks SQL VOID type."""
def __init__(self, value: None, name: Optional[str] = None):
"""
:value:
The value to bind for this parameter. This will be casted to a VOID.
:name:
If None, your query must contain a `?` marker. Like:
```sql
SELECT * FROM table WHERE field = ?
```
If not None, your query should contain a named parameter marker. Like:
```sql
SELECT * FROM table WHERE field = :my_param
```
The `name` argument to this function would be `my_param`.
"""
self.value = value
self.name = name
CAST_EXPR = DatabricksSupportedType.VOID.name
def _tspark_param_value(self):
"""For Void types, the TSparkParameter.value should be a Python NoneType"""
return None
class SmallIntParameter(DbsqlParameterBase):
"""Wrap a Python `int` that will be bound to a Databricks SQL SMALLINT type."""
def __init__(self, value: int, name: Optional[str] = None):
"""
:value:
The value to bind for this parameter. This will be casted to a SMALLINT.
:name:
If None, your query must contain a `?` marker. Like:
```sql
SELECT * FROM table WHERE field = ?
```
If not None, your query should contain a named parameter marker. Like:
```sql
SELECT * FROM table WHERE field = :my_param
```
The `name` argument to this function would be `my_param`.
"""
self.value = value
self.name = name
CAST_EXPR = DatabricksSupportedType.SMALLINT.name
class TimestampParameter(DbsqlParameterBase):
"""Wrap a Python `datetime` that will be bound to a Databricks SQL TIMESTAMP type."""
def __init__(self, value: datetime.datetime, name: Optional[str] = None):
"""
:value:
The value to bind for this parameter. This will be casted to a TIMESTAMP.
:name:
If None, your query must contain a `?` marker. Like:
```sql
SELECT * FROM table WHERE field = ?
```
If not None, your query should contain a named parameter marker. Like:
```sql
SELECT * FROM table WHERE field = :my_param
```
The `name` argument to this function would be `my_param`.
"""
self.value = value
self.name = name
CAST_EXPR = DatabricksSupportedType.TIMESTAMP.name
class TimestampNTZParameter(DbsqlParameterBase):
"""Wrap a Python `datetime` that will be bound to a Databricks SQL TIMESTAMP_NTZ type."""
def __init__(self, value: datetime.datetime, name: Optional[str] = None):
"""
:value:
The value to bind for this parameter. This will be casted to a TIMESTAMP_NTZ.
If it contains a timezone, that info will be lost.
:name:
If None, your query must contain a `?` marker. Like:
```sql
SELECT * FROM table WHERE field = ?
```
If not None, your query should contain a named parameter marker. Like:
```sql
SELECT * FROM table WHERE field = :my_param
```
The `name` argument to this function would be `my_param`.
"""
self.value = value
self.name = name
CAST_EXPR = DatabricksSupportedType.TIMESTAMP_NTZ.name
class TinyIntParameter(DbsqlParameterBase):
"""Wrap a Python `int` that will be bound to a Databricks SQL TINYINT type."""
def __init__(self, value: int, name: Optional[str] = None):
"""
:value:
The value to bind for this parameter. This will be casted to a TINYINT.
:name:
If None, your query must contain a `?` marker. Like:
```sql
SELECT * FROM table WHERE field = ?
```
If not None, your query should contain a named parameter marker. Like:
```sql
SELECT * FROM table WHERE field = :my_param
```
The `name` argument to this function would be `my_param`.
"""
self.value = value
self.name = name
CAST_EXPR = DatabricksSupportedType.TINYINT.name
class ArrayParameter(DbsqlParameterBase):
"""Wrap a Python `Sequence` that will be bound to a Databricks SQL ARRAY type."""
def __init__(self, value: Sequence[Any], name: Optional[str] = None):
"""
:value:
The value to bind for this parameter. This will be casted to a ARRAY.
:name:
If None, your query must contain a `?` marker. Like:
```sql
SELECT * FROM table WHERE field = ?
```
If not None, your query should contain a named parameter marker. Like:
```sql
SELECT * FROM table WHERE field = :my_param
```
The `name` argument to this function would be `my_param`.
"""
self.name = name
self.value = [dbsql_parameter_from_primitive(val) for val in value]
def as_tspark_param(self, named: bool = False) -> TSparkParameter:
"""Returns a TSparkParameter object that can be passed to the DBR thrift server."""
tsp = TSparkParameter(type=self._cast_expr())
tsp.arguments = [val._tspark_value_arg() for val in self.value]
if named:
tsp.name = self.name
tsp.ordinal = False
elif not named:
tsp.ordinal = True
return tsp
def _tspark_value_arg(self):
"""Returns a TSparkParameterValueArg object that can be passed to the DBR thrift server."""
tva = TSparkParameterValueArg(type=self._cast_expr())
tva.arguments = [val._tspark_value_arg() for val in self.value]
return tva
CAST_EXPR = DatabricksSupportedType.ARRAY.name
class MapParameter(DbsqlParameterBase):
"""Wrap a Python `dict` that will be bound to a Databricks SQL MAP type."""
def __init__(self, value: dict, name: Optional[str] = None):
"""
:value:
The value to bind for this parameter. This will be casted to a MAP.
:name:
If None, your query must contain a `?` marker. Like:
```sql
SELECT * FROM table WHERE field = ?
```
If not None, your query should contain a named parameter marker. Like:
```sql
SELECT * FROM table WHERE field = :my_param
```
The `name` argument to this function would be `my_param`.
"""
self.name = name
self.value = [
dbsql_parameter_from_primitive(item)
for key, val in value.items()
for item in (key, val)
]
def as_tspark_param(self, named: bool = False) -> TSparkParameter:
"""Returns a TSparkParameter object that can be passed to the DBR thrift server."""
tsp = TSparkParameter(type=self._cast_expr())
tsp.arguments = [val._tspark_value_arg() for val in self.value]
if named:
tsp.name = self.name
tsp.ordinal = False
elif not named:
tsp.ordinal = True
return tsp
def _tspark_value_arg(self):
"""Returns a TSparkParameterValueArg object that can be passed to the DBR thrift server."""
tva = TSparkParameterValueArg(type=self._cast_expr())
tva.arguments = [val._tspark_value_arg() for val in self.value]
return tva
CAST_EXPR = DatabricksSupportedType.MAP.name
class DecimalParameter(DbsqlParameterBase):
"""Wrap a Python `Decimal` that will be bound to a Databricks SQL DECIMAL type."""
CAST_EXPR = "DECIMAL({},{})"
def __init__(
self,
value: decimal.Decimal,
name: Optional[str] = None,
scale: Optional[int] = None,
precision: Optional[int] = None,
):
"""
If set, `scale` and `precision` must both be set. If neither is set, the value
will be casted to the smallest possible DECIMAL type that can contain it.
:value:
The value to bind for this parameter. This will be casted to a DECIMAL.
:name:
If None, your query must contain a `?` marker. Like:
```sql
SELECT * FROM table WHERE field = ?
```
If not None, your query should contain a named parameter marker. Like:
```sql
SELECT * FROM table WHERE field = :my_param
```
The `name` argument to this function would be `my_param`.
:scale:
The maximum precision (total number of digits) of the number between 1 and 38.
:precision:
The number of digits to the right of the decimal point.
"""
self.value: decimal.Decimal = value
self.name = name
self.scale = scale
self.precision = precision
if not self.valid_scale_and_precision():
raise ValueError(
"DecimalParameter requires both or none of scale and precision to be set"
)
def valid_scale_and_precision(self):
if (self.scale is None and self.precision is None) or (
isinstance(self.scale, int) and isinstance(self.precision, int)
):
return True
else:
return False
def _cast_expr(self):
if self.scale and self.precision:
return self.CAST_EXPR.format(self.scale, self.precision)
else:
return self.calculate_decimal_cast_string(self.value)
def calculate_decimal_cast_string(self, input: decimal.Decimal) -> str:
"""Returns the smallest SQL cast argument that can contain the passed decimal
Example:
Input: Decimal("1234.5678")
Output: DECIMAL(8,4)
"""
string_decimal = str(input)
if string_decimal.startswith("0."):
# This decimal is less than 1
overall = after = len(string_decimal) - 2
elif "." not in string_decimal:
# This decimal has no fractional component
overall = len(string_decimal)
after = 0
else:
# This decimal has both whole and fractional parts
parts = string_decimal.split(".")
parts_lengths = [len(i) for i in parts]
before, after = parts_lengths[:2]
overall = before + after
return self.CAST_EXPR.format(overall, after)
def dbsql_parameter_from_int(value: int, name: Optional[str] = None):
"""Returns IntegerParameter unless the passed int() requires a BIGINT.
Note: TinyIntegerParameter is never inferred here because it is a rarely used type and clauses like LIMIT and OFFSET
cannot accept TINYINT bound parameter values.
"""
if -128 <= value <= 127:
# If DBR is ever updated to permit TINYINT values passed to LIMIT and OFFSET
# then we can change this line to return TinyIntParameter
return IntegerParameter(value=value, name=name)
elif -2147483648 <= value <= 2147483647:
return IntegerParameter(value=value, name=name)
else:
return BigIntegerParameter(value=value, name=name)
def dbsql_parameter_from_primitive(
value: TAllowedParameterValue, name: Optional[str] = None
) -> "TDbsqlParameter":
"""Returns a DbsqlParameter subclass given an inferrable value
This is a convenience function that can be used to create a DbsqlParameter subclass
without having to explicitly import a subclass of DbsqlParameter.
"""
# This series of type checks are required for mypy not to raise
# havoc. We can't use TYPE_INFERRENCE_MAP because mypy doesn't trust
# its logic
if isinstance(value, bool):
return BooleanParameter(value=value, name=name)
elif isinstance(value, int):
return dbsql_parameter_from_int(value, name=name)
elif isinstance(value, str):
return StringParameter(value=value, name=name)
elif isinstance(value, float):
return FloatParameter(value=value, name=name)
elif isinstance(value, datetime.datetime):
return TimestampParameter(value=value, name=name)
elif isinstance(value, datetime.date):
return DateParameter(value=value, name=name)
elif isinstance(value, decimal.Decimal):
return DecimalParameter(value=value, name=name)
elif isinstance(value, dict):
return MapParameter(value=value, name=name)
elif isinstance(value, Sequence) and not isinstance(value, str):
return ArrayParameter(value=value, name=name)
elif value is None:
return VoidParameter(value=value, name=name)
else:
raise NotSupportedError(
f"Could not infer parameter type from value: {value} - {type(value)} \n"
"Please specify the type explicitly."
)
TDbsqlParameter = Union[
IntegerParameter,
StringParameter,
BigIntegerParameter,
BooleanParameter,
DateParameter,
DoubleParameter,
FloatParameter,
VoidParameter,
SmallIntParameter,
TimestampParameter,
TimestampNTZParameter,
TinyIntParameter,
DecimalParameter,
ArrayParameter,
MapParameter,
]
TParameterSequence = Sequence[Union[TDbsqlParameter, TAllowedParameterValue]]
TParameterDict = Dict[str, TAllowedParameterValue]
TParameterCollection = Union[TParameterSequence, TParameterDict]
_all__ = [
"IntegerParameter",
"StringParameter",
"BigIntegerParameter",
"BooleanParameter",
"DateParameter",
"DoubleParameter",
"FloatParameter",
"VoidParameter",
"SmallIntParameter",
"TimestampParameter",
"TimestampNTZParameter",
"TinyIntParameter",
"DecimalParameter",
]