|
| 1 | +import logging |
| 2 | +import math |
| 3 | + |
| 4 | +from .database_types import * |
| 5 | +from .base import MD5_HEXDIGITS, CHECKSUM_HEXDIGITS, Database, import_helper, _query_conn, parse_table_name |
| 6 | + |
| 7 | + |
| 8 | +@import_helper("databricks") |
| 9 | +def import_databricks(): |
| 10 | + import databricks.sql |
| 11 | + |
| 12 | + return databricks |
| 13 | + |
| 14 | + |
| 15 | +class Databricks(Database): |
| 16 | + TYPE_CLASSES = { |
| 17 | + # Numbers |
| 18 | + "INT": Integer, |
| 19 | + "SMALLINT": Integer, |
| 20 | + "TINYINT": Integer, |
| 21 | + "BIGINT": Integer, |
| 22 | + "FLOAT": Float, |
| 23 | + "DOUBLE": Float, |
| 24 | + "DECIMAL": Decimal, |
| 25 | + # Timestamps |
| 26 | + "TIMESTAMP": Timestamp, |
| 27 | + # Text |
| 28 | + "STRING": Text, |
| 29 | + } |
| 30 | + |
| 31 | + ROUNDS_ON_PREC_LOSS = True |
| 32 | + |
| 33 | + def __init__( |
| 34 | + self, |
| 35 | + http_path: str, |
| 36 | + access_token: str, |
| 37 | + server_hostname: str, |
| 38 | + catalog: str = "hive_metastore", |
| 39 | + schema: str = "default", |
| 40 | + **kwargs, |
| 41 | + ): |
| 42 | + databricks = import_databricks() |
| 43 | + |
| 44 | + self._conn = databricks.sql.connect( |
| 45 | + server_hostname=server_hostname, http_path=http_path, access_token=access_token |
| 46 | + ) |
| 47 | + |
| 48 | + logging.getLogger("databricks.sql").setLevel(logging.WARNING) |
| 49 | + |
| 50 | + self.catalog = catalog |
| 51 | + self.default_schema = schema |
| 52 | + self.kwargs = kwargs |
| 53 | + |
| 54 | + def _query(self, sql_code: str) -> list: |
| 55 | + "Uses the standard SQL cursor interface" |
| 56 | + return _query_conn(self._conn, sql_code) |
| 57 | + |
| 58 | + def quote(self, s: str): |
| 59 | + return f"`{s}`" |
| 60 | + |
| 61 | + def md5_to_int(self, s: str) -> str: |
| 62 | + return f"cast(conv(substr(md5({s}), {1+MD5_HEXDIGITS-CHECKSUM_HEXDIGITS}), 16, 10) as decimal(38, 0))" |
| 63 | + |
| 64 | + def to_string(self, s: str) -> str: |
| 65 | + return f"cast({s} as string)" |
| 66 | + |
| 67 | + def _convert_db_precision_to_digits(self, p: int) -> int: |
| 68 | + # Subtracting 1 due to wierd precision issues |
| 69 | + return max(super()._convert_db_precision_to_digits(p) - 1, 0) |
| 70 | + |
| 71 | + def query_table_schema(self, path: DbPath, filter_columns: Optional[Sequence[str]] = None) -> Dict[str, ColType]: |
| 72 | + # Databricks has INFORMATION_SCHEMA only for Databricks Runtime, not for Databricks SQL. |
| 73 | + # https://docs.databricks.com/spark/latest/spark-sql/language-manual/information-schema/columns.html |
| 74 | + # So, to obtain information about schema, we should use another approach. |
| 75 | + |
| 76 | + schema, table = self._normalize_table_path(path) |
| 77 | + with self._conn.cursor() as cursor: |
| 78 | + cursor.columns(catalog_name=self.catalog, schema_name=schema, table_name=table) |
| 79 | + rows = cursor.fetchall() |
| 80 | + if not rows: |
| 81 | + raise RuntimeError(f"{self.name}: Table '{'.'.join(path)}' does not exist, or has no columns") |
| 82 | + |
| 83 | + if filter_columns is not None: |
| 84 | + accept = {i.lower() for i in filter_columns} |
| 85 | + rows = [r for r in rows if r.COLUMN_NAME.lower() in accept] |
| 86 | + |
| 87 | + resulted_rows = [] |
| 88 | + for row in rows: |
| 89 | + row_type = "DECIMAL" if row.DATA_TYPE == 3 else row.TYPE_NAME |
| 90 | + type_cls = self.TYPE_CLASSES.get(row_type, UnknownColType) |
| 91 | + |
| 92 | + if issubclass(type_cls, Integer): |
| 93 | + row = (row.COLUMN_NAME, row_type, None, None, 0) |
| 94 | + |
| 95 | + elif issubclass(type_cls, Float): |
| 96 | + numeric_precision = self._convert_db_precision_to_digits(row.DECIMAL_DIGITS) |
| 97 | + row = (row.COLUMN_NAME, row_type, None, numeric_precision, None) |
| 98 | + |
| 99 | + elif issubclass(type_cls, Decimal): |
| 100 | + # TYPE_NAME has a format DECIMAL(x,y) |
| 101 | + items = row.TYPE_NAME[8:].rstrip(")").split(",") |
| 102 | + numeric_precision, numeric_scale = int(items[0]), int(items[1]) |
| 103 | + row = (row.COLUMN_NAME, row_type, None, numeric_precision, numeric_scale) |
| 104 | + |
| 105 | + elif issubclass(type_cls, Timestamp): |
| 106 | + row = (row.COLUMN_NAME, row_type, row.DECIMAL_DIGITS, None, None) |
| 107 | + |
| 108 | + else: |
| 109 | + row = (row.COLUMN_NAME, row_type, None, None, None) |
| 110 | + |
| 111 | + resulted_rows.append(row) |
| 112 | + col_dict: Dict[str, ColType] = {row[0]: self._parse_type(path, *row) for row in resulted_rows} |
| 113 | + |
| 114 | + self._refine_coltypes(path, col_dict) |
| 115 | + return col_dict |
| 116 | + |
| 117 | + def normalize_timestamp(self, value: str, coltype: TemporalType) -> str: |
| 118 | + """Databricks timestamp contains no more than 6 digits in precision""" |
| 119 | + |
| 120 | + if coltype.rounds: |
| 121 | + timestamp = f"cast(round(unix_micros({value}) / 1000000, {coltype.precision}) * 1000000 as bigint)" |
| 122 | + return f"date_format(timestamp_micros({timestamp}), 'yyyy-MM-dd HH:mm:ss.SSSSSS')" |
| 123 | + else: |
| 124 | + precision_format = "S" * coltype.precision + "0" * (6 - coltype.precision) |
| 125 | + return f"date_format({value}, 'yyyy-MM-dd HH:mm:ss.{precision_format}')" |
| 126 | + |
| 127 | + def normalize_number(self, value: str, coltype: NumericType) -> str: |
| 128 | + return self.to_string(f"cast({value} as decimal(38, {coltype.precision}))") |
| 129 | + |
| 130 | + def parse_table_name(self, name: str) -> DbPath: |
| 131 | + path = parse_table_name(name) |
| 132 | + return self._normalize_table_path(path) |
| 133 | + |
| 134 | + def close(self): |
| 135 | + self._conn.close() |
0 commit comments