|
| 1 | +import re |
| 2 | +import logging |
| 3 | +from collections.abc import Mapping |
| 4 | +from datetime import datetime |
| 5 | + |
| 6 | +from pyspark.errors import PySparkException |
| 7 | +from pyspark.sql import DataFrame, DataFrameReader, SparkSession |
| 8 | +from pyspark.sql.functions import col |
| 9 | +from sqlglot import Dialect |
| 10 | + |
| 11 | +from databricks.labs.lakebridge.reconcile.connectors.data_source import DataSource |
| 12 | +from databricks.labs.lakebridge.reconcile.connectors.jdbc_reader import JDBCReaderMixin |
| 13 | +from databricks.labs.lakebridge.reconcile.connectors.models import NormalizedIdentifier |
| 14 | +from databricks.labs.lakebridge.reconcile.connectors.secrets import SecretsMixin |
| 15 | +from databricks.labs.lakebridge.reconcile.connectors.dialect_utils import DialectUtils |
| 16 | +from databricks.labs.lakebridge.reconcile.recon_config import JdbcReaderOptions, Schema, OptionalPrimitiveType |
| 17 | +from databricks.sdk import WorkspaceClient |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | +_SCHEMA_QUERY = """SELECT |
| 22 | + column_name, |
| 23 | + CASE |
| 24 | + WHEN data_type = 'numeric' AND numeric_precision IS NOT NULL |
| 25 | + THEN 'decimal(' || numeric_precision || ',' || numeric_scale || ')' |
| 26 | + WHEN data_type = 'real' |
| 27 | + THEN 'float' |
| 28 | + WHEN data_type = 'double precision' |
| 29 | + THEN 'double' |
| 30 | + WHEN data_type = 'character varying' AND character_maximum_length IS NOT NULL |
| 31 | + THEN 'varchar(' || character_maximum_length || ')' |
| 32 | + WHEN data_type = 'character' AND character_maximum_length IS NOT NULL |
| 33 | + THEN 'char(' || character_maximum_length || ')' |
| 34 | + WHEN data_type IN ('varbyte') |
| 35 | + THEN 'binary' |
| 36 | + ELSE data_type |
| 37 | + END AS data_type |
| 38 | + FROM |
| 39 | + information_schema.columns |
| 40 | + WHERE |
| 41 | + LOWER(table_name) = LOWER('{table}') |
| 42 | + AND LOWER(table_schema) = LOWER('{schema}') |
| 43 | + ORDER BY ordinal_position |
| 44 | + """ |
| 45 | + |
| 46 | + |
| 47 | +class RedshiftDataSource(DataSource, SecretsMixin, JDBCReaderMixin): |
| 48 | + _DRIVER = "redshift" |
| 49 | + _IDENTIFIER_DELIMITER = "\"" |
| 50 | + |
| 51 | + def __init__( |
| 52 | + self, |
| 53 | + engine: Dialect, |
| 54 | + spark: SparkSession, |
| 55 | + ws: WorkspaceClient, |
| 56 | + secret_scope: str, |
| 57 | + ): |
| 58 | + self._engine = engine |
| 59 | + self._spark = spark |
| 60 | + self._ws = ws |
| 61 | + self._secret_scope = secret_scope |
| 62 | + |
| 63 | + @property |
| 64 | + def get_jdbc_url(self) -> str: |
| 65 | + return ( |
| 66 | + f"jdbc:{RedshiftDataSource._DRIVER}://{self._get_secret('host')}" |
| 67 | + f":{self._get_secret('port')}/{self._get_secret('database')}" |
| 68 | + ) |
| 69 | + |
| 70 | + def read_data( |
| 71 | + self, |
| 72 | + catalog: str | None, |
| 73 | + schema: str, |
| 74 | + table: str, |
| 75 | + query: str, |
| 76 | + options: JdbcReaderOptions | None, |
| 77 | + ) -> DataFrame: |
| 78 | + # Redshift dialect in SQLGlot converts :tbl to %(tbl)s (PostgreSQL parameter syntax) |
| 79 | + table_query = query.replace("%(tbl)s", f"{schema}.{table}").replace(":tbl", f"{schema}.{table}") |
| 80 | + try: |
| 81 | + if options is None: |
| 82 | + df = self.reader(table_query).load() |
| 83 | + else: |
| 84 | + reader_options = self._get_jdbc_reader_options(options) |
| 85 | + df = self.reader(table_query, reader_options).load() |
| 86 | + return df.select([col(c).alias(c.lower()) for c in df.columns]) |
| 87 | + except (RuntimeError, PySparkException) as e: |
| 88 | + return self.log_and_throw_exception(e, "data", table_query) |
| 89 | + |
| 90 | + def get_schema( |
| 91 | + self, |
| 92 | + catalog: str | None, |
| 93 | + schema: str, |
| 94 | + table: str, |
| 95 | + normalize: bool = True, |
| 96 | + ) -> list[Schema]: |
| 97 | + schema_query = re.sub( |
| 98 | + r'\s+', |
| 99 | + ' ', |
| 100 | + _SCHEMA_QUERY.format(schema=schema, table=table), |
| 101 | + ) |
| 102 | + try: |
| 103 | + logger.debug(f"Fetching schema using query: \n`{schema_query}`") |
| 104 | + logger.info(f"Fetching Schema: Started at: {datetime.now()}") |
| 105 | + df = self.reader(schema_query).load() |
| 106 | + schema_metadata = df.select([col(c).alias(c.lower()) for c in df.columns]).collect() |
| 107 | + logger.info(f"Schema fetched successfully. Completed at: {datetime.now()}") |
| 108 | + return [self._map_meta_column(field, normalize) for field in schema_metadata] |
| 109 | + except (RuntimeError, PySparkException) as e: |
| 110 | + return self.log_and_throw_exception(e, "schema", schema_query) |
| 111 | + |
| 112 | + def reader(self, query: str, options: Mapping[str, OptionalPrimitiveType] | None = None) -> DataFrameReader: |
| 113 | + if options is None: |
| 114 | + options = {} |
| 115 | + user = self._get_secret('user') |
| 116 | + password = self._get_secret('password') |
| 117 | + return self._get_jdbc_reader( |
| 118 | + query, self.get_jdbc_url, RedshiftDataSource._DRIVER, {**options, "user": user, "password": password} |
| 119 | + ) |
| 120 | + |
| 121 | + def normalize_identifier(self, identifier: str) -> NormalizedIdentifier: |
| 122 | + return DialectUtils.normalize_identifier( |
| 123 | + identifier, |
| 124 | + source_start_delimiter=RedshiftDataSource._IDENTIFIER_DELIMITER, |
| 125 | + source_end_delimiter=RedshiftDataSource._IDENTIFIER_DELIMITER, |
| 126 | + ) |
0 commit comments