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

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

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

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

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

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

ローカル プロトタイピング: ローカル インスタンスにデータをシードする

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

ムービー レビュー アプリを使用可能にするには、結合やその他のオペレーションを複数のテーブルでリアルなデータを使用して行うクエリとミューテーションの プロトタイピングを行うために、映画、レビュー、ユーザーのデータが必要です。スキーマを拡張してデータベースにシードできます。

SQL Connect

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

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

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

_insertMany ミューテーションと _upsertMany ミューテーションを使用して、個々のデータベース テーブルを一度に 1 つずつ更新することも、結合関係で関連する複数のテーブルを更新することもできます。これらのユースケースと例を示すのに役立つ、拡張されたムービー レビュー アプリのスキーマを以下に示します。開始時の Movie型を超えてschema.gqlを拡張し、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 オペレーションを使用して、テーブルに多くのレコードを追加する方が合理的です。ムービー レビュー アプリの例では、これにより MovieActor にデータの初期セットが挿入されます。

次のミューテーションを実行するには、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"
    }
  ])
}

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

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

これを行うには、プロトタイプ コードでテーブルにレコードを追加しない場合は、 _upsertMany ミューテーションを使用します。SQL Connect

次の例では、初期値で 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 SQL Connect を使用できるように、Firebase では Admin SDK を設定することをおすすめします。Node.js 用の を 設定するAdmin SDK必要があります。

Admin SDK の使用方法については、他の SQL Connect ユースケースをご覧ください。

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

一括データ管理用の 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",
  },
  {
      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);

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

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

データのインポートについては、Cloud SQL for PostgreSQL ガイドをご覧ください

次のステップ