1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

testcontainers + drizzle で postgresqlのマイグレーションをテスト準備で行ったメモ

Posted at

概要

前回はテストコード中にpgを使ってテーブルの初期設定を行った。
今回はDrizzleのマイグレーションを使ってテーブルの初期設定を行う。

この時点のソース

ソース

pps/backend/test/integration.spec.ts
  // 省略
  beforeAll(async () => {
    // PostgreSQLコンテナを起動
    postgresContainer = await new PostgreSqlContainer('postgres:17.4-alpine')
      .withDatabase('test_db')
      .withUsername('test_user')
      .withPassword('test_password')
      .start();

    connectionString = postgresContainer.getConnectionUri();
+    await setupDb(connectionString);
+    await execSql(
+      connectionString,
+      `
+       INSERT INTO odyssage.users (id, name) VALUES ('${testUserId}', '${testUserName}');
+       INSERT INTO odyssage.scenarios (id, title, user_id, updated_at) VALUES ('${testScenarioId}', '${testScenarioTitle}', '${testUserId}', CURRENT_TIMESTAMP)
+      `,
+    );

    // アプリを初期化
    app = new Hono();
    app.route('/api/sessions', sessionRoute);
  }, 60000); // コンテナ起動に時間がかかるためタイムアウトを延長

  // テスト終了後にコンテナを停止
  afterAll(async () => {
    await postgresContainer.stop();
  });
// 省略
packages/database/test-utils/setupDb.ts
import * as path from 'path';
import { drizzle } from 'drizzle-orm/postgres-js';
import { migrate } from 'drizzle-orm/postgres-js/migrator';

export async function setupDb(connectionString: string) {
  const db = drizzle(connectionString);

  await migrate(db, {
    migrationsFolder: path.join(__dirname, '../migrations'), // drizzle.config.tsで指定したものと同じ
  });
}

packages/database/test-utils/execSql.ts
import { sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/postgres-js';

export async function execSql(connectionString: string, sqlText: string) {
  const db = drizzle(connectionString);
  await db.execute(sql.raw(sqlText));
}

参考

drizzle-orm
使い捨てテストDB環境のtestcontainersをPostgresql + Honoで試してみたメモ
Drizzle ORM でダミーデータを流し込む方法
postgres

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?