データをシードし、一括データ オペレーションを実行する

Firebase Data Connect では、一括データ オペレーションはミューテーションを使用して実行されます。Data Connect プロジェクトが PostgreSQL にデータを保存している場合でも、SQL ステートメントや SQL ツールを使用してデータを一括読み込むことはできません。Data Connect サービスとそのスキーマはデータベースと同期状態を維持する必要があります。PostgreSQL で直接操作すると、この同期が破棄されます。

Data Connect では、ミューテーションを使用してデータをシードし、一括データを管理します。ワークフローと環境に応じて、さまざまな方法でデータ管理ミューテーションを作成して呼び出すことができます。

  • ローカル開発では、アプリのプロトタイプを作成するときに、VS Code 拡張機能、Data Connect エミュレータ、ローカル データベース インスタンスを使用して、ローカル開発環境でデータ シーディング ミューテーションを作成して呼び出すことができます。

  • 本番環境開発では、大規模な CI/CD フローを実行し、本番環境データを管理する場合は、Firebase Admin SDK を使用できます。これは、特権環境で実行される一連のライブラリです。

ローカル開発: ローカル インスタンスにシードデータを設定する

スタートガイドでは、アドホック挿入ミューテーションを使用して 1 つのレコードを 1 つのテーブルに追加するアプリを設定しました。

映画レビュー アプリを使えるようにするには、映画、レビュー、ユーザーのデータが必要です。このデータを使用して、現実的なデータを含む複数のテーブルに対して結合などのオペレーションを使用するクエリとミューテーションのプロトタイプを作成します。スキーマを拡張してデータベースにシードできます。

プロトタイプ環境には、データ シーディングを実行するコードが必要です。このガイドでは、次のようなサンプルを示します。

  • 個々のテーブルで _insertMany_upsertMany を使用する
  • 関連テーブルでの _insertMany の使用

映画レビュー アプリのスキーマを更新する

_insertMany ミューテーションと _upsertMany ミューテーションを使用して、個々のデータベース テーブルを 1 つずつ更新したり、結合関係で関連する複数のテーブルを更新したりできます。これらのユースケースと例を説明するために、映画レビュー アプリのスキーマを拡張したものを以下に示します。これにより、schema.gql が開始 Movie 型を超えて Actor 型と MovieActor 型に拡張され、より複雑なクエリのプロトタイプを作成できるようになります。

# Actors
# Suppose an actor can participate in multiple movies and movies can have multiple actors
# Movie - Actors (or vice versa) is a many to many relationship
type Actor @table {
  id: UUID!
  imageUrl: String! 
  name: String! @col(name: "name", dataType: "varchar(30)")
}

# Join table for many-to-many relationship for movies and actors
# The 'key' param signifies the primary key(s) of this table
# In this case, the keys are [movieId, actorId], the generated fields of the reference types [movie, actor]
type MovieActor @table(key: ["movie", "actor"]) {
  # @ref creates a field in the current table (MovieActor) that holds the primary key of the referenced type
  # In this case, @ref(fields: "movieId", references: "id") is implied
  movie: Movie!
  # movieId: UUID! <- this is created by the implied @ref
  actor: Actor!
  # actorId: UUID! <- this is created by the implied @ref
  role: String! # "main" or "supporting"
}

ミューテーションを書き込んでゼロ状態のデータをシードする

プロトタイピング中に、クエリとミューテーションをさまざまな離散値に対してテストする必要がある場合は、複数のレコードでデータを入力できます。たとえば、比較とフィルタリングをテストするために、さまざまなジャンルと評価の映画レコードを複数追加できます。

Movie テーブルと Actor テーブルにシードデータを挿入する

プロトタイピングの段階に応じて、スタートガイドで説明した手法と同じ方法で 1 ~ 2 つのレコードを挿入できます。つまり、VS Code 拡張機能の CodeLenses を使用して _insert ミューテーションを作成し、データをハードコードし、VS Code でミューテーションを実行できます。

最終的には、_insertMany オペレーションを使用してテーブルに多くのレコードを追加することをおすすめします。映画レビュー アプリの例では、最初のデータセットが MovieActor に挿入されます。

次のミューテーションを実行するには、VS Code Firebase 拡張機能を使用して、適切なファイル エディタ ビューで、本番環境サービスまたはローカル データベースでプロトタイプを作成するかどうかに応じて、[Run (Production)] または [Run (Local)] CodeLens ボタンをクリックします。

# insertMany for Movie
# 2 records shown
mutation {
  movie_insertMany(data: [
    {
      id: "550e8400-e29b-41d4-a716-446655440000",
      title: "Inception",
      imageUrl: "https://firebasestorage.googleapis.com/v0/b/fdc-quickstart-web.appspot.com/o/movies%2Finception.jpg?alt=media&token=07b09781-b302-4623-a5c3-1956d0143168",
      genre: "sci-fi",
    },
    {
      id: "550e8400-e29b-41d4-a716-446655440001",
      title: "The Matrix",
      imageUrl: "https://firebasestorage.googleapis.com/v0/b/fdc-quickstart-web.appspot.com/o/movies%2Fthe_matrix.jpg?alt=media&token=4975645d-fef8-409e-84a5-bcc1046e2059",
      genre: "action",
    }
  ])
}
# insertMany for Actor
# 2 records shown
mutation {
  actor_insertMany(data: [
    {
      id: "123e4567-e89b-12d3-a456-426614174000",
      imageUrl: "https://firebasestorage.googleapis.com/v0/b/fdc-quickstart-web.appspot.com/o/actors%2Fdicaprio.jpeg?alt=media&token=452e030a-efa5-4ef4-bb81-502b23241316",
      name: "Leonardo DiCaprio"
    },
    {
      id: "123e4567-e89b-12d3-a456-426614174001",
      imageUrl: "https://firebasestorage.googleapis.com/v0/b/fdc-quickstart-web.appspot.com/o/actors%2Fkeanu.jpg?alt=media&token=6056520c-ef3e-4823-aad0-108aab163115",
      name: "Keanu Reeves"
    }
   ])
}

MovieActor 結合テーブルにデータをシードする

結合などの複雑なオペレーションを使用してクエリとミューテーションをテストするには、MovieActor テーブルに複数のレコードを追加します。

ここで、このような関係で複数のテーブルを更新する場合は、@transaction ディレクティブを追加して、更新が正常に完了するようにすることができます。

mutation @transaction {
  movie_insertMany(data: [
    {
      id: "550e8400-e29b-41d4-a716-446655440000",
      title: "Inception",
      imageUrl: "https://firebasestorage.googleapis.com/v0/b/fdc-quickstart-web.appspot.com/o/movies%2Finception.jpg?alt=media&token=07b09781-b302-4623-a5c3-1956d0143168",
      genre: "sci-fi",
    },
    {
      id: "550e8400-e29b-41d4-a716-446655440001",
      title: "The Matrix",
      imageUrl: "https://firebasestorage.googleapis.com/v0/b/fdc-quickstart-web.appspot.com/o/movies%2Fthe_matrix.jpg?alt=media&token=4975645d-fef8-409e-84a5-bcc1046e2059",
      genre: "action",
    }
  ])

  actor_insertMany(data: [
    {
      id: "123e4567-e89b-12d3-a456-426614174000",
      imageUrl: "https://firebasestorage.googleapis.com/v0/b/fdc-quickstart-web.appspot.com/o/actors%2Fdicaprio.jpeg?alt=media&token=452e030a-efa5-4ef4-bb81-502b23241316",
      name: "Leonardo DiCaprio"
    },
    {
      id: "123e4567-e89b-12d3-a456-426614174001",
      imageUrl: "https://firebasestorage.googleapis.com/v0/b/fdc-quickstart-web.appspot.com/o/actors%2Fkeanu.jpg?alt=media&token=6056520c-ef3e-4823-aad0-108aab163115",
      name: "Keanu Reeves"
    }
  ])
}

シードデータをリセットするミューテーションを作成する

プロトタイプを作成し、CI/CD を実行する際に、新しいデータセットで新しい一連のテストを行うために、データをゼロ状態にリセットすると便利です。

そのためには、プロトタイプ コードでテーブルにレコードを追加しない場合は、Data Connect が提供する _upsertMany ミューテーションを使用します。

次の例では、初期値を指定して movie_upsertMany を呼び出し、映画レコードを元の状態に更新します。

mutation {
  # Execute an upsertMany operation to update the Movie table
  movie_upsertMany(data: [
    {
      id: "550e8400-e29b-41d4-a716-446655440000",
      title: "Inception",
      imageUrl: "https://firebasestorage.googleapis.com/v0/b/fdc-quickstart-web.appspot.com/o/movies%2Finception.jpg?alt=media&token=07b09781-b302-4623-a5c3-1956d0143168",
      genre: "sci-fi",
    },
    {
      id: "550e8400-e29b-41d4-a716-446655440001",
      title: "The Matrix",
      imageUrl: "https://firebasestorage.googleapis.com/v0/b/fdc-quickstart-web.appspot.com/o/movies%2Fthe_matrix.jpg?alt=media&token=4975645d-fef8-409e-84a5-bcc1046e2059",
      genre: "action",
    }
   
}

本番環境開発: Admin SDK を使用してデータを入力して更新する

Firebase Admin SDK は、特権環境から作業する場合に使用できます。これは、本番環境データに対する一括データ オペレーションの重要性を考えると、数千のレコードを読み込む場合に重要なユースケースです。

Firebase Admin SDK をインストールする

主にローカルで作業する場合でも、ローカル環境を含む特権環境から Firebase Data Connect を使用できるように Admin SDK を設定することをおすすめします。Node.js の Admin SDK を設定する必要があります。

詳しくは、他の Data Connect ユースケースでの Admin SDK の使用をご覧ください。

本番環境データの一括読み込みと更新を行う

一括データ管理用の API は、ローカルにいくつかの行を追加するために前述の executeGraphQL API を使用して mutation {...} 文字列を構築するよう求めるわけではなく、代わりに GraphQL ミューテーションを構築します。

管理 API の大きな利点は、CI/CD フロー用のデータ配列を個別に管理して再利用したり、本番環境データ用の大規模な一括データファイルを設定したりできることです。

次のスニペットは、一括データ スクリプトを設定する方法を示しています。

import { initializeApp } from 'firebase-admin/app';
import { getDataConnect } from 'firebase-admin/data-connect';

const app = initializeApp();

const dc = getDataConnect({ location: "us-west2", serviceId: "my-service" });

const data = [
 {
      id: "550e8400-e29b-41d4-a716-446655440000",
      title: "Inception",
      imageUrl: "https://firebasestorage.googleapis.com/v0/b/fdc-quickstart-web.appspot.com/o/movies%2Finception.jpg?alt=media&token=07b09781-b302-4623-a5c3-1956d0143168",
      genre: "sci-fi",
  },
  {
      id: "550e8400-e29b-41d4-a716-446655440001",
      title: "The Matrix",
      imageUrl: "https://firebasestorage.googleapis.com/v0/b/fdc-quickstart-web.appspot.com/o/movies%2Fthe_matrix.jpg?alt=media&token=4975645d-fef8-409e-84a5-bcc1046e2059",
      genre: "action",
    }
];

// Methods of the bulk operations API
const resp = await dc.insert("movie" /*table name*/, data[0]);
// Or
const resp = await dc.insertMany("movie" /*table name*/, data);

// Or
const resp = await dc.upsert("movie" /*table name*/, data[0]);
// Or
const resp = await dc.upsertMany("movie" /*table name*/, data);

次のステップ