-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathfabric_connection_manager.py
514 lines (413 loc) · 15.4 KB
/
fabric_connection_manager.py
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
import datetime as dt
import struct
import time
from contextlib import contextmanager
from itertools import chain, repeat
from typing import Any, Callable, Dict, Mapping, Optional, Tuple, Union
import agate
import dbt.exceptions
import pyodbc
from azure.core.credentials import AccessToken
from azure.identity import (
AzureCliCredential,
ClientSecretCredential,
DefaultAzureCredential,
EnvironmentCredential,
ManagedIdentityCredential,
)
from dbt.adapters.sql import SQLConnectionManager
from dbt.clients.agate_helper import empty_table
from dbt.contracts.connection import AdapterResponse, Connection, ConnectionState
from dbt.events import AdapterLogger
from dbt.adapters.fabric import __version__
from dbt.adapters.fabric.fabric_credentials import FabricCredentials
AZURE_CREDENTIAL_SCOPE = "https://database.windows.net//.default"
_TOKEN: Optional[AccessToken] = None
AZURE_AUTH_FUNCTION_TYPE = Callable[[FabricCredentials], AccessToken]
logger = AdapterLogger("fabric")
# https://github.com/mkleehammer/pyodbc/wiki/Data-Types
datatypes = {
# "str": "char",
"str": "varchar",
"uuid.UUID": "uniqueidentifier",
"uuid": "uniqueidentifier",
# "float": "real",
# "float": "float",
"float": "bigint",
# "int": "smallint",
# "int": "tinyint",
"int": "int",
"bytes": "varbinary",
"bool": "bit",
"datetime.date": "date",
"datetime.datetime": "datetime2(6)",
"datetime.time": "time",
"decimal.Decimal": "decimal",
# "decimal.Decimal": "numeric",
}
def convert_bytes_to_mswindows_byte_string(value: bytes) -> bytes:
"""
Convert bytes to a Microsoft windows byte string.
Parameters
----------
value : bytes
The bytes.
Returns
-------
out : bytes
The Microsoft byte string.
"""
encoded_bytes = bytes(chain.from_iterable(zip(value, repeat(0))))
return struct.pack("<i", len(encoded_bytes)) + encoded_bytes
def convert_access_token_to_mswindows_byte_string(token: AccessToken) -> bytes:
"""
Convert an access token to a Microsoft windows byte string.
Parameters
----------
token : AccessToken
The token.
Returns
-------
out : bytes
The Microsoft byte string.
"""
value = bytes(token.token, "UTF-8")
return convert_bytes_to_mswindows_byte_string(value)
def get_cli_access_token(credentials: FabricCredentials) -> AccessToken:
"""
Get an Azure access token using the CLI credentials
First login with:
```bash
az login
```
Parameters
----------
credentials: FabricConnectionManager
The credentials.
Returns
-------
out : AccessToken
Access token.
"""
_ = credentials
token = AzureCliCredential().get_token(AZURE_CREDENTIAL_SCOPE)
return token
def get_msi_access_token(credentials: FabricCredentials) -> AccessToken:
"""
Get an Azure access token from the system's managed identity
Parameters
-----------
credentials: FabricCredentials
Credentials.
Returns
-------
out : AccessToken
The access token.
"""
token = ManagedIdentityCredential().get_token(AZURE_CREDENTIAL_SCOPE)
return token
def get_auto_access_token(credentials: FabricCredentials) -> AccessToken:
"""
Get an Azure access token automatically through azure-identity
Parameters
-----------
credentials: FabricCredentials
Credentials.
Returns
-------
out : AccessToken
The access token.
"""
token = DefaultAzureCredential().get_token(AZURE_CREDENTIAL_SCOPE)
return token
def get_environment_access_token(credentials: FabricCredentials) -> AccessToken:
"""
Get an Azure access token by reading environment variables
Parameters
-----------
credentials: FabricCredentials
Credentials.
Returns
-------
out : AccessToken
The access token.
"""
token = EnvironmentCredential().get_token(AZURE_CREDENTIAL_SCOPE)
return token
def get_sp_access_token(credentials: FabricCredentials) -> AccessToken:
"""
Get an Azure access token using the SP credentials.
Parameters
----------
credentials : FabricCredentials
Credentials.
Returns
-------
out : AccessToken
The access token.
"""
token = ClientSecretCredential(
str(credentials.tenant_id), str(credentials.client_id), str(credentials.client_secret)
).get_token(AZURE_CREDENTIAL_SCOPE)
return token
AZURE_AUTH_FUNCTIONS: Mapping[str, AZURE_AUTH_FUNCTION_TYPE] = {
"serviceprincipal": get_sp_access_token,
"cli": get_cli_access_token,
"msi": get_msi_access_token,
"auto": get_auto_access_token,
"environment": get_environment_access_token,
}
def get_pyodbc_attrs_before(credentials: FabricCredentials) -> Dict:
"""
Get the pyodbc attrs before.
Parameters
----------
credentials : FabricCredentials
Credentials.
Returns
-------
out : Dict
The pyodbc attrs before.
Source
------
Authentication for SQL server with an access token:
https://docs.microsoft.com/en-us/sql/connect/odbc/using-azure-active-directory?view=sql-server-ver15#authenticating-with-an-access-token
"""
global _TOKEN
attrs_before: Dict
MAX_REMAINING_TIME = 300
authentication = str(credentials.authentication).lower()
if authentication in AZURE_AUTH_FUNCTIONS:
time_remaining = (_TOKEN.expires_on - time.time()) if _TOKEN else MAX_REMAINING_TIME
if _TOKEN is None or (time_remaining < MAX_REMAINING_TIME):
azure_auth_function = AZURE_AUTH_FUNCTIONS[authentication]
_TOKEN = azure_auth_function(credentials)
token_bytes = convert_access_token_to_mswindows_byte_string(_TOKEN)
sql_copt_ss_access_token = 1256 # see source in docstring
attrs_before = {sql_copt_ss_access_token: token_bytes}
else:
attrs_before = {}
return attrs_before
def bool_to_connection_string_arg(key: str, value: bool) -> str:
"""
Convert a boolean to a connection string argument.
Parameters
----------
key : str
The key to use in the connection string.
value : bool
The boolean to convert.
Returns
-------
out : str
The connection string argument.
"""
return f'{key}={"Yes" if value else "No"}'
def byte_array_to_datetime(value: bytes) -> dt.datetime:
"""
Converts a DATETIMEOFFSET byte array to a timezone-aware datetime object
Parameters
----------
value : buffer
A binary value conforming to SQL_SS_TIMESTAMPOFFSET_STRUCT
Returns
-------
out : datetime
Source
------
SQL_SS_TIMESTAMPOFFSET datatype and SQL_SS_TIMESTAMPOFFSET_STRUCT layout:
https://learn.microsoft.com/sql/relational-databases/native-client-odbc-date-time/data-type-support-for-odbc-date-and-time-improvements
"""
# unpack 20 bytes of data into a tuple of 9 values
tup = struct.unpack("<6hI2h", value)
# construct a datetime object
return dt.datetime(
year=tup[0],
month=tup[1],
day=tup[2],
hour=tup[3],
minute=tup[4],
second=tup[5],
microsecond=tup[6] // 1000, # https://bugs.python.org/issue15443
tzinfo=dt.timezone(dt.timedelta(hours=tup[7], minutes=tup[8])),
)
class FabricConnectionManager(SQLConnectionManager):
TYPE = "fabric"
@contextmanager
def exception_handler(self, sql):
try:
yield
except pyodbc.DatabaseError as e:
logger.debug("Database error: {}".format(str(e)))
try:
# attempt to release the connection
self.release()
except pyodbc.Error:
logger.debug("Failed to release connection!")
raise dbt.exceptions.DbtDatabaseError(str(e).strip()) from e
except Exception as e:
logger.debug(f"Error running SQL: {sql}")
logger.debug("Rolling back transaction.")
self.release()
if isinstance(e, dbt.exceptions.DbtRuntimeError):
# during a sql query, an internal to dbt exception was raised.
# this sounds a lot like a signal handler and probably has
# useful information, so raise it without modification.
raise
raise dbt.exceptions.DbtRuntimeError(e)
@classmethod
def open(cls, connection: Connection) -> Connection:
if connection.state == ConnectionState.OPEN:
logger.debug("Connection is already open, skipping open.")
return connection
credentials = cls.get_credentials(connection.credentials)
con_str = [f"DRIVER={{{credentials.driver}}}"]
if "\\" in credentials.host:
# If there is a backslash \ in the host name, the host is a
# SQL Server named instance. In this case then port number has to be omitted.
con_str.append(f"SERVER={credentials.host}")
else:
con_str.append(f"SERVER={credentials.host},{credentials.port}")
con_str.append(f"Database={credentials.database}")
assert credentials.authentication is not None
if "ActiveDirectory" in credentials.authentication:
con_str.append(f"Authentication={credentials.authentication}")
if credentials.authentication == "ActiveDirectoryPassword":
con_str.append(f"UID={{{credentials.UID}}}")
con_str.append(f"PWD={{{credentials.PWD}}}")
elif credentials.authentication == "ActiveDirectoryInteractive":
con_str.append(f"UID={{{credentials.UID}}}")
elif credentials.windows_login:
con_str.append("trusted_connection=Yes")
elif credentials.authentication == "sql":
con_str.append(f"UID={{{credentials.UID}}}")
con_str.append(f"PWD={{{credentials.PWD}}}")
# https://docs.microsoft.com/en-us/sql/relational-databases/native-client/features/using-encryption-without-validation?view=sql-server-ver15
assert credentials.encrypt is not None
assert credentials.trust_cert is not None
con_str.append(bool_to_connection_string_arg("encrypt", credentials.encrypt))
con_str.append(
bool_to_connection_string_arg("TrustServerCertificate", credentials.trust_cert)
)
plugin_version = __version__.version
application_name = f"dbt-{credentials.type}/{plugin_version}"
con_str.append(f"APP={application_name}")
con_str_concat = ";".join(con_str)
index = []
for i, elem in enumerate(con_str):
if "pwd=" in elem.lower():
index.append(i)
if len(index) != 0:
con_str[index[0]] = "PWD=***"
con_str_display = ";".join(con_str)
retryable_exceptions = [ # https://github.com/mkleehammer/pyodbc/wiki/Exceptions
pyodbc.InternalError, # not used according to docs, but defined in PEP-249
pyodbc.OperationalError,
]
if credentials.authentication.lower() in AZURE_AUTH_FUNCTIONS:
# Temporary login/token errors fall into this category when using AAD
retryable_exceptions.append(pyodbc.InterfaceError)
def connect():
logger.debug(f"Using connection string: {con_str_display}")
attrs_before = get_pyodbc_attrs_before(credentials)
handle = pyodbc.connect(
con_str_concat,
attrs_before=attrs_before,
autocommit=True,
timeout=credentials.login_timeout,
)
handle.timeout = credentials.query_timeout
logger.debug(f"Connected to db: {credentials.database}")
return handle
return cls.retry_connection(
connection,
connect=connect,
logger=logger,
retry_limit=credentials.retries,
retryable_exceptions=retryable_exceptions,
)
def cancel(self, connection: Connection):
logger.debug("Cancel query")
def add_begin_query(self):
# return self.add_query('BEGIN TRANSACTION', auto_begin=False)
pass
def add_commit_query(self):
# return self.add_query('COMMIT TRANSACTION', auto_begin=False)
pass
def add_query(
self,
sql: str,
auto_begin: bool = True,
bindings: Optional[Any] = None,
abridge_sql_log: bool = False,
) -> Tuple[Connection, Any]:
connection = self.get_thread_connection()
if auto_begin and connection.transaction_open is False:
self.begin()
logger.debug('Using {} connection "{}".'.format(self.TYPE, connection.name))
with self.exception_handler(sql):
if abridge_sql_log:
logger.debug("On {}: {}....".format(connection.name, sql[0:512]))
else:
logger.debug("On {}: {}".format(connection.name, sql))
pre = time.time()
cursor = connection.handle.cursor()
# pyodbc does not handle a None type binding!
if bindings is None:
cursor.execute(sql)
else:
bindings = [
binding if not isinstance(binding, dt.datetime) else binding.isoformat()
for binding in bindings
]
cursor.execute(sql, bindings)
# convert DATETIMEOFFSET binary structures to datetime ojbects
# https://github.com/mkleehammer/pyodbc/issues/134#issuecomment-281739794
connection.handle.add_output_converter(-155, byte_array_to_datetime)
logger.debug(
"SQL status: {} in {:0.2f} seconds".format(
self.get_response(cursor), (time.time() - pre)
)
)
return connection, cursor
@classmethod
def get_credentials(cls, credentials: FabricCredentials) -> FabricCredentials:
return credentials
@classmethod
def get_response(cls, cursor: Any) -> AdapterResponse:
# message = str(cursor.statusmessage)
message = "OK"
rows = cursor.rowcount
# status_message_parts = message.split() if message is not None else []
# status_messsage_strings = [
# part
# for part in status_message_parts
# if not part.isdigit()
# ]
# code = ' '.join(status_messsage_strings)
return AdapterResponse(
_message=message,
# code=code,
rows_affected=rows,
)
@classmethod
def data_type_code_to_name(cls, type_code: Union[str, str]) -> str:
data_type = str(type_code)[str(type_code).index("'") + 1 : str(type_code).rindex("'")]
return datatypes[data_type]
def execute(
self, sql: str, auto_begin: bool = True, fetch: bool = False, limit: Optional[int] = None
) -> Tuple[AdapterResponse, agate.Table]:
_, cursor = self.add_query(sql, auto_begin)
response = self.get_response(cursor)
if fetch:
# Get the result of the first non-empty result set (if any)
while cursor.description is None:
if not cursor.nextset():
break
table = self.get_result_from_cursor(cursor, limit)
else:
table = empty_table()
# Step through all result sets so we process all errors
while cursor.nextset():
pass
return response, table