テーブルと列をカスタマイズする

SDK では、 カスタム テーブル と列の作成、更新、削除 (CUD) 操作、オプションのソリューションの関連付け、およびテーブル定義の取得と一覧表示がサポートされています。

カスタム テーブルを操作するためのコード例を見てみましょう。

# Create a custom table, including the customization prefix value in the schema names for the table and columns.
table_info = client.tables.create("new_Product", {
    "new_Code": "string",
    "new_Description": "memo",
    "new_Price": "decimal",
    "new_Active": "bool"
})

# Create with custom primary column name and solution assignment
table_info = client.tables.create(
    "new_Product",
    columns={
        "new_Code": "string",
        "new_Price": "decimal"
    },
    solution="MyPublisher",  # Optional: add to specific solution
    primary_column="new_ProductName",  # Optional: custom primary column (default is "{customization prefix value}_Name")
)

# Get table information
info = client.tables.get("new_Product")
print(f"Logical name: {info['table_logical_name']}")
print(f"Entity set: {info['entity_set_name']}")

# List all tables
tables = client.tables.list()
for table in tables:
    print(table)

# Add columns to existing table (columns must include customization prefix value)
client.tables.add_columns("new_Product", {"new_Category": "string"})

# Remove columns
client.tables.remove_columns("new_Product", ["new_Category"])

# List all columns (attributes) for a table to discover schema
columns = client.tables.list_columns("account")
for col in columns:
    print(f"{col['LogicalName']} ({col.get('AttributeType')})")

# List only specific properties
columns = client.tables.list_columns(
    "account",
    select=["LogicalName", "SchemaName", "AttributeType"],
    filter="AttributeType eq 'String'",
)

# Clean up
client.tables.delete("new_Product")

サポートされている列の種類

次の型文字列は、 create() および add_columns()で受け入れられます。

タイプ 使用可能なエイリアス
string text
memo multiline
int integer
decimal money
float double
bool boolean
datetime date
file —

オプションセット (選択) 列の場合は、 IntEnum サブクラス (またはメンバーに整数値を持つ Enum ) を文字列ではなく列型の値として直接渡します。 SDK では、クラス メンバーを使用してオプション セットの値を定義します。

from enum import IntEnum

class Priority(IntEnum):
    LOW = 1
    MEDIUM = 2
    HIGH = 3

table_info = client.tables.create("new_Task", {
    "new_Title": "string",
    "new_Priority": Priority,   # optionset column
})

列の制約を設定する

長さ、数値範囲、有効桁数、書式、必要なレベル、表示名などの制約を設定するには、ベア型文字列の代わりにディクショナリを渡します。 type キーは列の種類を保持し、残りのキーは制約を設定します。

Key 適用対象 Description
max_length string、memo 最大文字数。
min_value、max_value int、decimal、money、float 使用できる数値範囲。
precision decimal、money、float 小数点以下の桁数。
format string、int、datetime テキスト列の書式名 ( Email、 Url、 Phoneなど)、または整数列と日付/時刻列の形式。
required all 必要なレベル: None、 Recommended、または ApplicationRequired。
display_name all メーカー ポータルとアプリに表示される表示ラベル。
# Pass a dict spec to set constraints; a bare type string still works for simple columns.
client.tables.create("new_Feedback", {
    "new_Rating":  {"type": "int",  "min_value": 1, "max_value": 5},
    "new_Comment": {"type": "memo", "max_length": 2000, "display_name": "Comment"},
})

add_columns()やバッチ列の作成など、列型を指定できるあらゆる場所で dict 仕様を使用できます。

列定義を更新する

update_columnを使用して 1 つの列の制約を変更するか、update_columnsを使用して 1 回の呼び出しで複数の列を変更する。 どちらも、 createと同じオーバーライド キーを受け入れます。 SDK は要求を送信する前にすべての仕様を検証するため、無効なエントリがあると、前の列は変更されないまま、呼び出し全体が失敗します。

# Widen one column
client.tables.update_column("new_Feedback", "new_Comment", {"max_length": 4000})

# Update several columns at once
client.tables.update_columns("new_Feedback", {
    "new_Rating":  {"max_value": 10},
    "new_Comment": {"display_name": "Customer Comment"},
})

更新プログラムは、完全な列定義を取得し、変更を適用して、 MSCRM.MergeLabels ヘッダーを使用して完全な定義を Dataverse に送り返します。 他の言語のラベルは保持されるため、1 つのプロパティ ( max_length など) を変更しても、残りの列は変更されません。

型指定された列メタデータの読み取り

既定では、 list_columns と get_column は基本属性メタデータを返します。 typed=Trueを渡して、1 つの要求で型固有の定義を取得します。これには、テキスト列のMaxLength、または数値列のMinValueやMaxValueなどのプロパティが含まれます。

# One column, with its type-specific fields
col = client.tables.get_column("new_Feedback", "new_Comment", typed=True)
print(col["MaxLength"])   # 4000

# All columns, each with type-specific fields
cols = client.tables.list_columns("new_Feedback", typed=True)

Note

filter パラメーターは、既定の (typed=False) リストにのみ適用されます。 filterとtyped=Trueを組み合わせると、ValueErrorが発生します。

TableInfo の戻り値オブジェクト

client.tables.create() メソッドが TableInfo オブジェクトを返します。 プロパティに直接アクセスするか、旧バージョンとの互換性のために従来の dict-key 表記を使用します。

table_info = client.tables.create("new_Product", {"new_Code": "string"})

print(table_info.schema_name)       # new_Product
print(table_info.logical_name)      # new_product
print(table_info.entity_set_name)   # new_products
print(table_info.columns_created)   # ['new_Code', ...]

# Legacy dict-key access still works
print(table_info["table_schema_name"])

add_columns()メソッドと remove_columns() メソッドは、作成または削除する列名の一覧を返します。 get() メソッドは、テーブルのメタデータを返すか、テーブルが存在しない場合はNoneを返します。これにより、存在チェックに役立ちます。

代替キー

代替キーは、Dataverse で生成された GUID ではなく、1 つ以上のビジネス列によってレコードを識別します。 アップサート操作には代替キーが必要です。 table>Keys の下の Power Apps Maker ポータルで定義するか、client.tables.create_alternate_keyを使用してプログラムで定義します。

# Create an alternate key on the accountnumber column
key = client.tables.create_alternate_key(
    "account",
    "account_accountnumber_ak",
    ["accountnumber"],
    display_name="Account Number",
)
print(f"Created key {key.schema_name} ({key.metadata_id}), status={key.status}")

# The key status transitions from Pending to Active asynchronously - poll before upserting
for k in client.tables.get_alternate_keys("account"):
    if k.schema_name == "account_accountnumber_ak":
        print(f"{k.schema_name}: {k.status}")

Important

PendingからActiveへの移行はすぐには行われません。 作成直後にキーの状態を確認し、 Active されるまで待ってから upsert 要求を発行します。 アクティブな代替キーがない場合、Dataverse は 400 エラーで upsert 要求を拒否します。

Important

すべてのカスタム列名には、カスタマイズ プレフィックス値 ("new_" など) を含める必要があります。 この要件により、明示的で予測可能な名前付けが保証され、Dataverse メタデータの要件に合わせて調整されます。

カスタム テーブル メタデータの操作の詳細については、以下を参照してください。

  • tables.create は、新しいテーブルを記述する TableInfo オブジェクトを返します。 レコード ID は返されません。
  • tables.get は、テーブルが存在しない場合に None を返します。これにより、スキーマ設定はべき等になります。
  • tables.add_columns と tables.remove_columns は、変更された列名の一覧を返します。
  • tables.list_columns は、Web API PascalCase プロパティ名を使用する未加工の属性メタデータ ディクショナリ ( LogicalName や AttributeTypeなど) を返します。

テーブル内の レコード を作成、読み取り、更新、および削除するには、「 データの操作」を参照してください。

こちらも参照ください