forked from testcontainers/testcontainers-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostgresql-container.ts
More file actions
executable file
·189 lines (167 loc) · 6.38 KB
/
postgresql-container.ts
File metadata and controls
executable file
·189 lines (167 loc) · 6.38 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import { AbstractStartedContainer, GenericContainer, StartedTestContainer, Wait } from "testcontainers";
const POSTGRES_PORT = 5432;
export class PostgreSqlContainer extends GenericContainer {
private database = "test";
private username = "test";
private password = "test";
constructor(image = "postgres:13.3-alpine") {
super(image);
this.withExposedPorts(POSTGRES_PORT);
this.withWaitStrategy(Wait.forHealthCheck());
this.withStartupTimeout(120_000);
}
public withDatabase(database: string): this {
this.database = database;
return this;
}
public withUsername(username: string): this {
this.username = username;
return this;
}
public withPassword(password: string): this {
this.password = password;
return this;
}
public override async start(): Promise<StartedPostgreSqlContainer> {
this.withEnvironment({
POSTGRES_DB: this.database,
POSTGRES_USER: this.username,
POSTGRES_PASSWORD: this.password,
});
if (!this.healthCheck) {
this.withHealthCheck({
test: ["CMD-SHELL", `PGPASSWORD=${this.password} psql -U ${this.username} -d ${this.database} -c 'SELECT 1;'`],
interval: 250,
timeout: 1000,
retries: 1000,
});
}
return new StartedPostgreSqlContainer(await super.start(), this.database, this.username, this.password);
}
}
export class StartedPostgreSqlContainer extends AbstractStartedContainer {
private snapshotName: string = "migrated_template";
constructor(
startedTestContainer: StartedTestContainer,
private readonly database: string,
private readonly username: string,
private readonly password: string
) {
super(startedTestContainer);
}
public getPort(): number {
return super.getMappedPort(POSTGRES_PORT);
}
public getDatabase(): string {
return this.database;
}
public getUsername(): string {
return this.username;
}
public getPassword(): string {
return this.password;
}
/**
* @returns A connection URI in the form of `postgres[ql]://[username[:password]@][host[:port],]/database`
*/
public getConnectionUri(): string {
const url = new URL("", "postgres://");
url.hostname = this.getHost();
url.port = this.getPort().toString();
url.pathname = this.getDatabase();
url.username = this.getUsername();
url.password = this.getPassword();
return url.toString();
}
/**
* Sets the name to be used for database snapshots.
* This name will be used as the default for snapshot() and restore() methods.
*
* @param snapshotName The name to use for snapshots (default is "migrated_template" if this method is not called)
* @returns this (for method chaining)
*/
public withSnapshotName(snapshotName: string): this {
this.snapshotName = snapshotName;
return this;
}
/**
* Takes a snapshot of the current state of the database as a template, which can then be restored using
* the restore method.
*
* @param snapshotName Name for the snapshot, defaults to the value set by withSnapshotName() or "migrated_template" if not specified
* @returns Promise resolving when snapshot is complete
* @throws Error if attempting to snapshot the postgres system database or if using the same name as the database
*/
public async snapshot(snapshotName = this.snapshotName): Promise<void> {
this.snapshotSanityCheck(snapshotName);
// Execute the commands to create the snapshot, in order
await this.execCommandsSQL([
// Update pg_database to remove the template flag, then drop the database if it exists.
// This is needed because dropping a template database will fail.
`UPDATE pg_database SET datistemplate = FALSE WHERE datname = '${snapshotName}'`,
`DROP DATABASE IF EXISTS "${snapshotName}"`,
// Create a copy of the database to another database to use as a template now that it was fully migrated
`CREATE DATABASE "${snapshotName}" WITH TEMPLATE "${this.getDatabase()}" OWNER "${this.getUsername()}"`,
// Snapshot the template database so we can restore it onto our original database going forward
`ALTER DATABASE "${snapshotName}" WITH is_template = TRUE`,
]);
}
/**
* Restores the database to a specific snapshot.
*
* @param snapshotName Name of the snapshot to restore from, defaults to the value set by withSnapshotName() or "migrated_template" if not specified
* @returns Promise resolving when restore is complete
* @throws Error if attempting to restore the postgres system database or if using the same name as the database
*/
public async restore(snapshotName = this.snapshotName): Promise<void> {
this.snapshotSanityCheck(snapshotName);
// Execute the commands to restore the snapshot, in order
await this.execCommandsSQL([
// Drop the entire database by connecting to the postgres global database
`DROP DATABASE "${this.getDatabase()}" WITH (FORCE)`,
// Then restore the previous snapshot
`CREATE DATABASE "${this.getDatabase()}" WITH TEMPLATE "${snapshotName}" OWNER "${this.getUsername()}"`,
]);
}
/**
* Executes a series of SQL commands against the Postgres database
*
* @param commands Array of SQL commands to execute in sequence
* @throws Error if any command fails to execute with details of the failure
*/
private async execCommandsSQL(commands: string[]): Promise<void> {
for (const command of commands) {
try {
const result = await this.exec([
"psql",
"-v",
"ON_ERROR_STOP=1",
"-U",
this.getUsername(),
"-d",
"postgres",
"-c",
command,
]);
if (result.exitCode !== 0) {
throw new Error(`Command failed with exit code ${result.exitCode}: ${result.output}`);
}
} catch (error) {
console.error(`Failed to execute command: ${command}`, error);
throw error;
}
}
}
/**
* Checks if the snapshot name is valid and if the database is not the postgres system database
* @param snapshotName The name of the snapshot to check
*/
private snapshotSanityCheck(snapshotName: string): void {
if (this.getDatabase() === "postgres") {
throw new Error("Cannot restore the postgres system database as it cannot be dropped to be restored");
}
if (this.getDatabase() === snapshotName) {
throw new Error("Cannot restore the database to itself");
}
}
}