Connection To Microsoft Fabric Warehouse using Nodejs

184 Views Asked by At

I am trying to connect to a Microsoft Fabric Warehouse via the nodejs mssql package with the service principal authentication method. I have looked at this documentation [https://learn.microsoft.com/en-us/fabric/data-warehouse/connectivity][1] And I am able to connect to fabric warehouse using python and pyodbc library. But unfortunately the corresponding nodejs code is not working. I get an error like below

          err = new ConnectionError(err)
                ^

ConnectionError: Connection lost - socket hang up  

The nodejs code is given below

const sql = require('mssql');

const azureIdentity = require('@azure/identity');

const tenantId = process.env.TENANT_ID;
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
const dbServer = "<myfabricwarehouse>.datawarehouse.pbidedicated.windows.net";
const database = "<mydatabase>"



async function myfunc(){
    const credential = new azureIdentity.ClientSecretCredential(tenantId,clientId,clientSecret);
    const token = await credential.getToken(scopes="https://database.windows.net/.default");
    const sqlConfig = {
        database: database,
        server: dbServer,
        authentication: {
            type: "azure-active-directory-access-token",
            options: {
                token: token.token
                }
        },
        pool: {
            max: 10,
            min: 0,
            idleTimeoutMillis: 30000
        },
        options: {
            encrypt: true, 
            trustServerCertificate: false 
        }
    };

    const conn = await sql.connect(sqlConfig);
}


myfunc();

The python code that works fine for the same fabric warehouse and database is shown below

from azure.identity import ClientSecretCredential

import os , pyodbc , struct

client_secret = os.environ["CLIENT_SECRET"]
tenant_id = os.environ["TENANT_ID"]
client_id = os.environ["CLIENT_ID"]
database_server_name = "<myfabricwarehouse>.datawarehouse.pbidedicated.windows.net"
database_name = "mydatabase"
connection_string = f"Driver={{ODBC Driver 17 for SQL Server}};Server={database_server_name};Database={database_name};Port=1433,Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30"
try:
    credential = ClientSecretCredential(
       tenant_id=tenant_id,
       client_id=client_id,
       client_secret=client_secret
    )
    
    token_bytes = credential.get_token("https://database.windows.net/.default").token.encode("UTF-16-LE")
    token_struct = struct.pack(f'<I{len(token_bytes)}s', len(token_bytes), token_bytes)
    SQL_COPT_SS_ACCESS_TOKEN = 1256  # This connection option is defined by microsoft in msodbcsql.h

    
    conn = pyodbc.connect(connection_string, attrs_before={SQL_COPT_SS_ACCESS_TOKEN: token_struct})

except Exception as e:
    print(e)
0

There are 0 best solutions below