在 Microsoft Fabric HorizonDB 中建立資料表

本文將在 Fabric HorizonDB 中建立可重複使用的 PostgreSQL 範例結構描述。 這些資料表使用識別資料行、主鍵和外鍵、檢查條件約束、含時區的時間戳記,以及索引。

Important

Fabric HorizonDB 目前處於公開預覽階段。 功能、限制與行為可能會在正式推出前發生變化。 如需更多資訊,請參閱 Microsoft Fabric 預覽功能。

Prerequisites

  • 一個 HorizonDB 資料庫。
  • 存取 SQL 編輯器或其他 PostgreSQL 用戶端。
  • 以資料庫建立者身分登入。 其他使用者與安全性主體無法在目前預覽版中連線至 PostgreSQL。

建立範例結構

開啟一個新查詢並執行:

CREATE SCHEMA IF NOT EXISTS horizon_sample;

使用專用結構描述可將範例與由服務管理的結構描述及應用程式結構描述分開。

建立客戶資料表

CREATE TABLE IF NOT EXISTS horizon_sample.customers (
    customer_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer_name text NOT NULL UNIQUE,
    segment text NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);

此資料表使用 PostgreSQL 識別欄位作為其代理主鍵。 唯一限制條件可防止此範例中出現重複的客戶名稱。

建立訂單表

CREATE TABLE IF NOT EXISTS horizon_sample.orders (
    order_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    order_reference text NOT NULL UNIQUE,
    customer_id bigint NOT NULL
        REFERENCES horizon_sample.customers (customer_id),
    order_date date NOT NULL DEFAULT current_date,
    status text NOT NULL
        CHECK (status IN ('open', 'processing', 'completed', 'cancelled')),
    total numeric(12, 2) NOT NULL
        CHECK (total >= 0),
    created_at timestamptz NOT NULL DEFAULT now()
);

外鍵可防止訂單參照不存在的客戶。 檢查約束可保護狀態詞彙並防止負總數。

新增索引

主鍵與唯一限制條件本身就會建立索引。 新增索引以符合常見的客戶與日期存取模式:

CREATE INDEX IF NOT EXISTS ix_orders_customer_date
ON horizon_sample.orders (customer_id, order_date DESC);

沒有工作負載上的理由時,不要新增索引。 每個索引都會消耗儲存空間,並為插入、更新、VACUUM 與鏡像複寫增加工作量。

確認物件

檢查欄:

SELECT
    table_name,
    column_name,
    data_type,
    is_nullable,
    column_default
FROM information_schema.columns
WHERE table_schema = 'horizon_sample'
  AND table_name IN ('customers', 'orders')
ORDER BY table_name, ordinal_position;

檢視限制條件:

SELECT
    table_name,
    constraint_name,
    constraint_type
FROM information_schema.table_constraints
WHERE table_schema = 'horizon_sample'
ORDER BY table_name, constraint_type, constraint_name;

預期結果包括兩個資料表上的主鍵、從 orders 到 customers的外鍵、唯一約束條件以及檢查約束。

重新整理物件總管,展開 結構描述、展開 horizon_sample,以及展開 資料表。 選取 customers 或 orders 檢查欄位與鍵。

了解所有權與存取權

建立物件的身分通常是其擁有者。 擁有權允許進行強大的變更,包括刪除物件。

目前預覽版中,只有建立資料庫的 Microsoft Entra 身份才能連線。 分享 Fabric 項目不會啟用額外的 PostgreSQL 使用者。 不要為了繞過這個限制而建立登入角色。

如需更多資訊,請參閱 驗證 PostgreSQL 存取。

清理

執行前請檢視結構名稱:

DROP SCHEMA IF EXISTS horizon_sample CASCADE;

CASCADE 刪除結構中的所有物件。 不要在服務管理或應用程式結構描述上使用它。

下一步

載入範例資料。