ibis-project / ibis

the portable Python dataframe library
https://ibis-project.org
Apache License 2.0
5.35k stars 600 forks source link

docs: document mssql Azure Active Directory authentication #9455

Open inigohidalgo opened 5 months ago

inigohidalgo commented 5 months ago

Please describe the issue

https://github.com/ibis-project/ibis/issues/7381#issuecomment-1766582531

Some additional configuration/munging is needed to enable authentication to azure SQL services. We should add a section to the documentation explaining how this is done


import struct
from azure import identity
import sqlalchemy as sa

SQL_COPT_SS_ACCESS_TOKEN = 1256 # Connection option for access tokens, as defined in msodbcsql.h TOKEN_URL = "https://database.windows.net/" # The token URL for any Azure SQL database

azure_credentials = identity.DefaultAzureCredential()

def provide_token(dialect, conn_rec, cargs, cparams): """sqlalchemy.event.listens_for(ibis_conn.con, "do_connect")(provide_token) """

remove the "Trusted_Connection" parameter that SQLAlchemy adds

cargs[0] = cargs[0].replace(";Trusted_Connection=Yes", "")

# create token credential
raw_token = azure_credentials.get_token(TOKEN_URL).token.encode("utf-16-le")
token_struct = struct.pack(f"<I{len(raw_token)}s", len(raw_token), raw_token)

# apply it to keyword arguments
cparams["attrs_before"] = {SQL_COPT_SS_ACCESS_TOKEN: token_struct}

def make_ibis_connection_login_ad_interactive(conn): sa.event.listens_for(conn.con, "do_connect")(provide_token)


```python
raw_conn = ibis.connect(
    f"mssql://{os.environ['SERVER_NAME_ENV']}/{os.environ['DB_NAME_ENV']}",
    query = {
        "driver": "ODBC Driver 17 for SQL Server",
    }
)
make_ibis_connection_login_ad_interactive(raw_conn)

Code of Conduct

inigohidalgo commented 5 months ago

@cpcloud I can't assign issues, could you assign me? thx

cpcloud commented 5 months ago

Done