Skip to content

Instantly share code, notes, and snippets.

@MarkPryceMaherMSFT
Last active September 28, 2024 09:23
Show Gist options
  • Save MarkPryceMaherMSFT/e3e2be7f23981131b570d098f0e6d5ed to your computer and use it in GitHub Desktop.
Save MarkPryceMaherMSFT/e3e2be7f23981131b570d098f0e6d5ed to your computer and use it in GitHub Desktop.
Script that gets the sql endpoint for a workspace and lakehouse
import pandas as pd
import struct
import sqlalchemy
import pyodbc
import notebookutils
import sempy.fabric as fabric
def create_engine(connection_string : str):
token = notebookutils.credentials.getToken('https://analysis.windows.net/powerbi/api').encode("UTF-16-LE")
token_struct = struct.pack(f'<I{len(token)}s', len(token), token)
SQL_COPT_SS_ACCESS_TOKEN = 1256
return sqlalchemy.create_engine("mssql+pyodbc://", creator=lambda: pyodbc.connect(connection_string, attrs_before={SQL_COPT_SS_ACCESS_TOKEN: token_struct}))
tenant_id=spark.conf.get("trident.tenant.id")
workspace_id=spark.conf.get("trident.workspace.id")
lakehouse_id=spark.conf.get("trident.lakehouse.id")
lakehouse_name=spark.conf.get("trident.lakehouse.name")
sql_endpoint= fabric.FabricRestClient().get(f"/v1/workspaces/{workspace_id}/lakehouses/{lakehouse_id}").json()['properties']['sqlEndpointProperties']['connectionString']
connection_string = f"Driver={{ODBC Driver 18 for SQL Server}};Server={sql_endpoint},1433;Encrypt=Yes;TrustServerCertificate=No"
print (f"connection_string={connection_string}")
engine = create_engine(connection_string)
df = pd.read_sql_query("SELECT DB_NAME() AS [Current Database]; ", engine)
display(df)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment