教學:將 PostgreSQL 應用程式連接到 Fabric HorizonDB

在此教學步驟中,您將將本地 Python 應用程式連接到 PostgreSQL 端點。 你會查詢兩個檢視:一個透過聯邦機制讀取資料倉儲訊號,另一個則讀取由 Copy 作業載入至 PostgreSQL 的訊號。

Important

Fabric HorizonDB 目前處於公開預覽階段。 只有建立資料庫的 Microsoft Entra 身份才能連線。 以建立者身分執行本機操作;在目前預覽版中,服務主體與受管理身份無法連線。

Prerequisites

  • 完成在筆記本中分析鏡像資料。
  • 保留來自同盟步驟的 fabric_sales.customer_signals,以及來自複製作業步驟的 analytics_ops.customer_signals。
  • 安裝 Python 3.10 或更新版本。
  • 設定 Connect with Python 中描述的連線值,包括租戶與預覽權杖範圍。

請使用來自 postgres 項目連線窗格的 PostgreSQL 主機,以及資料庫名稱 contoso-orders-db。 不要使用 Fabric 項目的顯示名稱或 SQL 分析端點。

建立應用程式檢視

請在 HorizonDB PostgreSQL 編輯器中執行此 SQL:

CREATE OR REPLACE VIEW horizon_sample.customer_analytics AS
SELECT
    customer.customer_id,
    customer.customer_name,
    signal.risk_score,
    signal.recommended_action,
    signal.calculated_at
FROM horizon_sample.customers AS customer
JOIN fabric_sales.customer_signals AS signal
  ON signal.customer_id = customer.customer_id;

CREATE OR REPLACE VIEW horizon_sample.customer_operational_insights AS
SELECT
    customer.customer_id,
    customer.customer_name,
    signal.risk_score,
    signal.recommended_action,
    signal.calculated_at
FROM horizon_sample.customers AS customer
JOIN analytics_ops.customer_signals AS signal
  ON signal.customer_id = customer.customer_id;

第一個檢視在查詢時具有遠端倉儲依賴。 第二個只讀取本地 PostgreSQL 資料表;其新鮮度取決於最後一次成功載入與發佈步驟。 這些檢視用來組織應用程式查詢;它們不會啟用額外的 PostgreSQL 使用者。

建立應用程式

建立名為 contoso-orders-app 的資料夾,建立並啟用虛擬環境,然後安裝:

python -m pip install "psycopg[binary]" azure-identity

創建 app.py:

import os
import sys

import psycopg
from azure.identity import InteractiveBrowserCredential


customer_id = int(sys.argv[1])

with InteractiveBrowserCredential(
    tenant_id=os.environ["HORIZONDB_TENANT_ID"]
) as credential:
    token = credential.get_token(
        os.environ["HORIZONDB_TOKEN_SCOPE"]
    ).token

    with psycopg.connect(
        host=os.environ["HORIZONDB_HOST"],
        port=int(os.environ["HORIZONDB_PORT"]),
        dbname=os.environ["HORIZONDB_DATABASE"],
        user=os.environ["HORIZONDB_USER"],
        password=token,
        sslmode=os.environ["HORIZONDB_SSLMODE"],
        connect_timeout=30,
        application_name="contoso-orders-app",
    ) as connection:
        with connection.cursor() as cursor:
            cursor.execute("SET statement_timeout = '30s'")
            cursor.execute(
                """
                SELECT customer_name, risk_score,
                       recommended_action, calculated_at
                FROM horizon_sample.customer_analytics
                WHERE customer_id = %s
                """,
                (customer_id,),
            )
            print("Federated result:", cursor.fetchall())

            cursor.execute(
                """
                SELECT customer_name, risk_score,
                       recommended_action, calculated_at
                FROM horizon_sample.customer_operational_insights
                WHERE customer_id = %s
                """,
                (customer_id,),
            )
            print("Loaded local result:", cursor.fetchall())

驅動程式將客戶 ID 綁定為參數。 不要將使用者輸入串接到 SQL、列印權杖,或將認證資訊儲存在原始碼中。

執行並驗證

載入連線環境的值,然後以來自 horizon_sample.customers 的實際客戶 ID 執行應用程式。 例如:

python app.py 1

在瀏覽器中以資料庫建立者身份登入。 確認兩個結果都與所選客戶的來源資料相符。 如果聯邦查詢失敗,請分別調查來源權限、容量與中繼資料,以及本機 PostgreSQL 的健康狀況。 範例中會顯示錯誤,而非悄無聲息地退回使用較舊的本機資料。

僅在安全、暫時性的連線失敗時使用有限制重試。 不要在未修正驗證或權限錯誤的情況下重試,也不要重播不確定的寫入交易。

預期結果

該應用程式使用單一 PostgreSQL 連線查詢聯邦分析訊號及已載入的作業訊號。 如果複製作業後倉庫有所變更,它們的數值可能會有所不同。

下一步