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

Firebase SQL Connect では、ワークフローと環境に応じて、さまざまな方法で一括データの読み込みと更新を行うことができます。

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

  • 本番環境の開発では、安定したスキーマを使用して、より大規模な CI / CD フローを実行し、本番環境データを管理する場合、次の 2 つのオプションがあります。

    • 推奨される方法は、特権環境で実行されるライブラリのセットである Firebase Admin SDK を使用することです。

    • データベース スキーマではなくデータを変更する場合は、Cloud SQL インスタンスで SQL ツールを使用して一括読み込みと更新を行うこともできます。SQL ツールを使用してデータベース スキーマを直接変更すると、SQL Connect スキーマとコネクタが破損する可能性があります。

ローカル プロトタイピング: ローカル インスタンスのシードデータ

スタートガイドでは、アドホック挿入ミューテーションを使用して、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 つのレコードを挿入できます。つまり、SQL Connect VS Code 拡張機能の CodeLens を使用して _insert ミューテーションを作成し、データをハードコードして、VS Code でそれらのミューテーションを実行できます。

最終的には、_insertMany オペレーションを使用してテーブルに多数のレコードを追加する方が理にかなっています。映画レビューアプリの例では、Movie と Actor に初期データセットが挿入されます。

次のミューテーションを実行するには、SQL Connect VS Code 拡張機能を使用して、適切なファイル エディタビューで、本番環境サービスまたはローカル データベースでプロトタイピングしているかどうかに応じて、[実行(本番環境)] または [実行(ローカル)] 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"
    }
  ])
}

関連テーブルをアトミックにシードするには、リテラル ペイロードを使用してネストされたリレーショナル挿入を実行します。これにより、手動で外部キーを関連付けることなく、親レコードとそれに関連付けられた子レコードが 1 回のオペレーションで作成されます。

1 対多の関係の場合は、ネストされた子レコードの配列を指定します。1 対 1 の関係の場合は、ネストされた子オブジェクトを 1 つ指定します。

# Nested insert for Movie and Review (one-to-many)
# 1 movie and 2 reviews shown
mutation {
  movie_insert(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",
    reviews_on_movie: [
      {
        id: "123e4567-e89b-12d3-a456-426614174002",
        rating: 5,
        reviewText: "Amazing concept!",
        user: { id: "user-uuid-123" }
      },
      {
        id: "123e4567-e89b-12d3-a456-426614174003",
        rating: 4,
        reviewText: "A bit confusing, but great.",
        user: { id: "user-uuid-456" }
      }
    ]
  })
}
# Nested insert for User and Profile (one-to-one)
mutation {
  user_insert(data: {
    id: "user-uuid-123",
    name: "Alice",
    profile_on_user: {
      bio: "Avid moviegoer and critic."
    }
  })
}

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

プロトタイピングと CI / CD の実行中に、データをゼロ状態にリセットして、新しいデータセットで新しい一連のテストを実行すると便利な場合があります。

プロトタイプ コードでテーブルにレコードを追加しない場合は、SQL 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 をインストールする

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

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

商品データの一括読み込みと更新を行う

一括データ マネジメント用の API は、GraphQL ミューテーションを自動的に作成します。前述の executeGraphQL API を使用して mutation {...} 文字列を作成し、ローカルで数行を追加する必要はありません。

管理 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",
    // Nested reviews can be inserted atomically along with the movie
    reviews_on_movie: [
      {
        rating: 5,
        reviewText: "Amazing concept!",
        user: { id: "user-123" } // Link to existing user
      }
    ]
  },
  {
    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",
    reviews_on_movie: [
      {
        rating: 5,
        reviewText: "A masterpiece of sci-fi action.",
        user: { id: "user-456" }
      }
    ]
  }
];

// 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);

本番環境の開発: SQL を使用してデータを一括更新する

本番環境で安定したスキーマを使用し、スキーマを変更しない場合は、Cloud SQL インスタンスで作業して、データの読み込みと更新を管理できます。

PostgreSQL 用 Cloud SQL のデータ インポート ガイドをご覧ください。

次のステップ