|
| 1 | +"""Azure SQL Database implementation of Base Hyper Extractor ABC |
| 2 | +
|
| 3 | +Tableau Community supported Hyper API sample |
| 4 | +
|
| 5 | +----------------------------------------------------------------------------- |
| 6 | +
|
| 7 | +This file is the copyrighted property of Tableau Software and is protected |
| 8 | +by registered patents and other applicable U.S. and international laws and |
| 9 | +regulations. |
| 10 | +
|
| 11 | +You may adapt this file and modify it to fit into your context and use it |
| 12 | +as a template to start your own projects. |
| 13 | +
|
| 14 | +----------------------------------------------------------------------------- |
| 15 | +""" |
| 16 | +import logging |
| 17 | +from typing import Any, Optional, Dict |
| 18 | + |
| 19 | +import pyodbc |
| 20 | +from tableauhyperapi import Nullability, SqlType, TableDefinition, TableName |
| 21 | + |
| 22 | +from base_extractor import DEFAULT_SITE_ID, BaseExtractor, HyperSQLTypeMappingError |
| 23 | + |
| 24 | +logger = logging.getLogger("hyper_samples.extractor.mySQL") |
| 25 | + |
| 26 | +class QuerySizeLimitError(Exception): |
| 27 | + pass |
| 28 | + |
| 29 | +class AzureSQLExtractor(BaseExtractor): |
| 30 | + """Azure SQL Database Implementation of Extractor Interface |
| 31 | +
|
| 32 | + Authentication to Tableau Server can be either by Personal Access Token or |
| 33 | + Username and Password. |
| 34 | +
|
| 35 | + Constructor Args: |
| 36 | + - source_database_config (dict): Source database parameters |
| 37 | + - tableau_hostname (string): URL for Tableau Server, e.g. "http://localhost" |
| 38 | + - tableau_site_id (string): Tableau site identifier - if default use "" |
| 39 | + - tableau_project (string): Tableau project identifier |
| 40 | + - tableau_token_name (string): PAT name |
| 41 | + - tableau_token_secret (string): PAT secret |
| 42 | + - tableau_username (string): Tableau username |
| 43 | + - tableau_password (string): Tableau password |
| 44 | + NOTE: Authentication to Tableau Server can be either by Personal Access Token or |
| 45 | + Username and Password. If both are specified then token takes precedence. |
| 46 | + """ |
| 47 | + |
| 48 | + def __init__( |
| 49 | + self, |
| 50 | + source_database_config: dict, |
| 51 | + tableau_hostname: str, |
| 52 | + tableau_project: str, |
| 53 | + tableau_site_id: str = DEFAULT_SITE_ID, |
| 54 | + tableau_token_name: Optional[str] = None, |
| 55 | + tableau_token_secret: Optional[str] = None, |
| 56 | + tableau_username: Optional[str] = None, |
| 57 | + tableau_password: Optional[str] = None, |
| 58 | + ) -> None: |
| 59 | + super().__init__( |
| 60 | + source_database_config=source_database_config, |
| 61 | + tableau_hostname=tableau_hostname, |
| 62 | + tableau_project=tableau_project, |
| 63 | + tableau_site_id=tableau_site_id, |
| 64 | + tableau_token_name=tableau_token_name, |
| 65 | + tableau_token_secret=tableau_token_secret, |
| 66 | + tableau_username=tableau_username, |
| 67 | + tableau_password=tableau_password, |
| 68 | + ) |
| 69 | + self._source_database_connection = None |
| 70 | + self.sql_identifier_quote = "" |
| 71 | + |
| 72 | + def source_database_cursor(self) -> Any: |
| 73 | + """ |
| 74 | + Returns a DBAPI Cursor to the source database |
| 75 | + """ |
| 76 | + assert self.source_database_config is not None |
| 77 | + if self._source_database_connection is None: |
| 78 | + logger.info("Connecting to source Azure SQL Database Instance...") |
| 79 | + |
| 80 | + db_connection_args = self.source_database_config.get("connection") |
| 81 | + assert type(db_connection_args) is dict |
| 82 | + |
| 83 | + key_vault_url = db_connection_args.get("key_vault_url") |
| 84 | + secret_name = db_connection_args.get("secret_name") |
| 85 | + if key_vault_url is not None: |
| 86 | + #Recommended: Read password from keyvault |
| 87 | + from azure.identity import DefaultAzureCredential |
| 88 | + from azure.keyvault.secrets import SecretClient |
| 89 | + credential = DefaultAzureCredential() |
| 90 | + secret_client = SecretClient(vault_url=key_vault_url, credential=credential) |
| 91 | + secret = secret_client.get_secret(secret_name) |
| 92 | + this_password = secret.value |
| 93 | + else: |
| 94 | + #Password is stored as plain text |
| 95 | + this_password = db_connection_args["password"] |
| 96 | + |
| 97 | + connection_str = "Driver={{ODBC Driver 17 for SQL Server}};Server={host},{port};Database={database};Uid={username};Pwd={password};{connect_str_suffix}".format( |
| 98 | + host=db_connection_args["host"], |
| 99 | + port=db_connection_args["port"], |
| 100 | + database=db_connection_args["database"], |
| 101 | + username=db_connection_args["username"], |
| 102 | + password=this_password, |
| 103 | + connect_str_suffix=db_connection_args["connect_str_suffix"] |
| 104 | + ) |
| 105 | + self._source_database_connection = pyodbc.connect(connection_str) |
| 106 | + |
| 107 | + return self._source_database_connection.cursor() |
| 108 | + |
| 109 | + def hyper_sql_type(self, source_column: Any) -> SqlType: |
| 110 | + """ |
| 111 | + Finds the corresponding Hyper column type for source_column |
| 112 | +
|
| 113 | + source_column (obj): Instance of DBAPI Column description tuple |
| 114 | +
|
| 115 | + Returns a tableauhyperapi.SqlType Object |
| 116 | + """ |
| 117 | + |
| 118 | + """ |
| 119 | + Note: pyodbc returns a description which contains a tuple per column with the following fields |
| 120 | + 0 column name (or alias, if specified in the SQL) |
| 121 | + 1 type object |
| 122 | + 2 display size (pyodbc does not set this value) |
| 123 | + 3 internal size (in bytes) |
| 124 | + 4 precision |
| 125 | + 5 scale |
| 126 | + 6 nullable (True/False) |
| 127 | + e.g. ('schema_id', <class 'int'>, None, 10, 10, 0, False) |
| 128 | + The mapping from SQL types to python types is defined in pyodbx.SQL_data_type_dict |
| 129 | + """ |
| 130 | + source_column_type = source_column[1].__name__ |
| 131 | + source_column_precision = source_column[4] |
| 132 | + source_column_scale = source_column[5] |
| 133 | + |
| 134 | + type_lookup = { |
| 135 | + "str": SqlType.text, |
| 136 | + "unicode": SqlType.text, |
| 137 | + "bytearray": SqlType.text, |
| 138 | + "bool": SqlType.bool, |
| 139 | + |
| 140 | + "int": SqlType.int, |
| 141 | + "float": SqlType.double, |
| 142 | + "long": SqlType.big_int, |
| 143 | + #"Decimal": SqlType.numeric, |
| 144 | + |
| 145 | + "date": SqlType.date, |
| 146 | + "time": SqlType.time, |
| 147 | + "datetime": SqlType.timestamp_tz, |
| 148 | + } |
| 149 | + |
| 150 | + if source_column_type == 'Decimal': |
| 151 | + return_sql_type = SqlType.numeric(source_column_precision, source_column_scale) |
| 152 | + else: |
| 153 | + return_sql_type = type_lookup.get(source_column_type) |
| 154 | + |
| 155 | + if return_sql_type is None: |
| 156 | + error_message = "No Hyper SqlType defined for MySQL source type: {}".format(source_column_type) |
| 157 | + logger.error(error_message) |
| 158 | + raise HyperSQLTypeMappingError(error_message) |
| 159 | + |
| 160 | + return_sql_type = return_sql_type() |
| 161 | + |
| 162 | + logger.debug("Translated source column type {} to Hyper SqlType {}".format(source_column_type, return_sql_type)) |
| 163 | + return return_sql_type |
| 164 | + |
| 165 | + def hyper_table_definition(self, source_table: Any, hyper_table_name: str = "Extract") -> TableDefinition: |
| 166 | + """ |
| 167 | + Build a hyper table definition from source_schema |
| 168 | +
|
| 169 | + source_table (obj): Source table (Instance of DBAPI Cursor Description) |
| 170 | + hyper_table_name (string): Name of the target Hyper table, default="Extract" |
| 171 | +
|
| 172 | + Returns a tableauhyperapi.TableDefinition Object |
| 173 | + """ |
| 174 | + logger.debug( |
| 175 | + "Building Hyper TableDefinition for table {}".format(source_table) |
| 176 | + ) |
| 177 | + target_cols = [] |
| 178 | + for source_column in source_table: |
| 179 | + this_name = source_column[0] |
| 180 | + this_type = self.hyper_sql_type(source_column) |
| 181 | + if source_column[6] == False: |
| 182 | + this_col = TableDefinition.Column(this_name, this_type, Nullability.NOT_NULLABLE) |
| 183 | + else: |
| 184 | + this_col = TableDefinition.Column(name=this_name, type=this_type) |
| 185 | + target_cols.append(this_col) |
| 186 | + logger.info("..Column {} - Type {}".format(this_name, this_type)) |
| 187 | + |
| 188 | + # Create the target schema for our Hyper File |
| 189 | + target_schema = TableDefinition(table_name=TableName("Extract", hyper_table_name), columns=target_cols) |
| 190 | + return target_schema |
| 191 | + |
| 192 | + def load_sample( |
| 193 | + self, |
| 194 | + tab_ds_name: str, |
| 195 | + source_table: Optional[str] = None, |
| 196 | + sql_query: Optional[str] = None, |
| 197 | + sample_rows: int = 0, |
| 198 | + publish_mode: Any = None, |
| 199 | + ) -> None: |
| 200 | + error_message = "METHOD load_sample is not implemented for SQL Server (Transact-SQL does not support the LIMIT statement)" |
| 201 | + logger.error(error_message) |
| 202 | + raise NotImplementedError(error_message) |
| 203 | + |
| 204 | +def main(): |
| 205 | + pass |
| 206 | + |
| 207 | + |
| 208 | +if __name__ == "__main__": |
| 209 | + main() |
0 commit comments