-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlc_pg_tx.test.ts
78 lines (66 loc) · 2.09 KB
/
sqlc_pg_tx.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { Client } from 'pg'
import { GenericContainer, Wait } from 'testcontainers'
import { expect, test } from 'vitest'
import fs from 'node:fs'
import {
createAccount,
deleteAccount,
getAccount,
listAccounts,
} from '../src/gen/sqlc/pg/account_sql'
test('account', async () => {
// PostgreSQL コンテナを起動
const container = await new GenericContainer('postgres:latest')
.withEnvironment({
POSTGRES_DB: 'testdb',
POSTGRES_USER: 'user',
POSTGRES_PASSWORD: 'password',
})
.withExposedPorts(5432)
// TCPポートが利用可能になるまで待機
.withWaitStrategy(Wait.forListeningPorts())
.start()
// postgres クライアントの設定
const client = new Client({
host: container.getHost(),
port: container.getMappedPort(5432),
database: 'testdb',
user: 'user',
password: 'password',
})
await client.connect()
// データベースへの ping (接続テスト)
await client.query('SELECT 1')
// ファイルを読み込んでSQL文を取得
const schemaSQL = fs.readFileSync('db/schema.sql', 'utf-8')
// スキーマの初期化
await client.query(schemaSQL)
try {
await client.query('BEGIN')
await createAccount(client, { id: 'spam', displayName: 'Egg', email: 'ham@example.com' })
const account = await getAccount(client, { id: 'spam' })
await client.query('COMMIT')
expect(account).not.toBeNull()
// ここダサい、なんかいい書き方 Vitest にありそう
if (account) {
expect(account.id).toBe('spam')
expect(account.displayName).toBe('Egg')
expect(account.email).toBe('ham@example.com')
}
} catch (e) {
await client.query('ROLLBACK')
}
try {
await client.query('BEGIN')
await deleteAccount(client, { id: 'spam' })
throw new Error('rollback')
} catch (e) {
await client.query('ROLLBACK')
}
const accounts = await listAccounts(client)
// ロールバックされており、データが残っている
expect(accounts.length).toBe(1)
await client.end()
// コンテナを停止
await container.stop()
}, 30_000)