1 import { Client } from "@medusajs/framework/pg"
2
3 const DB_HOST = process.env.DB_HOST ?? "localhost"
4 const DB_USERNAME = process.env.DB_USERNAME ?? "postgres"
5 const DB_PASSWORD = process.env.DB_PASSWORD ?? ""
6 const DB_PORT = process.env.DB_PORT ?? "5432"
7 const DB_WAITINGROOM_DATABASE =
8 process.env.DB_WAITINGROOM_DATABASE ?? "postgres"
9
10 type DatabaseTemplateOptions = {
11 databaseName: string
12 templateName: string
13 }
14
15 function quoteIdentifier(identifier: string) {
16 if (!identifier) {
17 throw new Error("Database identifier cannot be empty")
18 }
19
20 return `"${identifier.replace(/"/g, '""')}"`
21 }
22
23 // We need to connect to a different database while creating and restoring a template.
24 // The client is created lazily and reused across calls, since restores run before every
25 // test and reconnecting each time adds 10-30ms per test.
26 let waitingroomClientPromise: Promise<Client> | null = null
27
28 function resetWaitingroomClient() {
29 waitingroomClientPromise = null
30 }
31
32 async function getWaitingroomClient(): Promise<Client> {
33 if (!waitingroomClientPromise) {
34 waitingroomClientPromise = (async () => {
35 const client = new Client({
36 host: DB_HOST,
37 user: DB_USERNAME,
38 password: DB_PASSWORD || undefined,
39 port: parseInt(DB_PORT),
40 database: DB_WAITINGROOM_DATABASE,
41 })
42
43 try {
44 await client.connect()
45 } catch (error) {
46 resetWaitingroomClient()
47 throw error
48 }
49
50 // If the connection drops, make sure the next call reconnects.
51 client.on("error", resetWaitingroomClient)
52 client.on("end", resetWaitingroomClient)
53
54 return client
55 })()
56 }
57
58 return waitingroomClientPromise
59 }
60
61 export async function closeWaitingroomClient() {
62 if (!waitingroomClientPromise) {
63 return
64 }
65
66 const clientPromise = waitingroomClientPromise
67 resetWaitingroomClient()
68
69 const client = await clientPromise.catch(() => null)
70 await client?.end().catch(() => void 0)
71 }
72
73 const MAX_DROP_ATTEMPTS = 10
74
75 const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
76
77 async function terminateDatabaseConnections(
78 client: Client,
79 databaseName: string
80 ) {
81 await client.query(
82 `SELECT pg_terminate_backend(pid)
83 FROM pg_stat_activity
84 WHERE datname = $1
85 AND pid <> pg_backend_pid();`,
86 [databaseName]
87 )
88 }
89
90 async function cancelAndTerminateDatabaseConnections(
91 client: Client,
92 databaseName: string
93 ) {
94 await client.query(
95 `SELECT pg_cancel_backend(pid)
96 FROM pg_stat_activity
97 WHERE datname = $1
98 AND pid <> pg_backend_pid();`,
99 [databaseName]
100 )
101
102 await terminateDatabaseConnections(client, databaseName)
103 }
104
105 async function setAllowConnections(
106 client: Client,
107 databaseName: string,
108 allowConnections: boolean
109 ) {
110 await client.query(
111 `ALTER DATABASE ${quoteIdentifier(
112 databaseName
113 )} WITH ALLOW_CONNECTIONS ${allowConnections};`
114 )
115 }
116
117 async function dropDatabaseIfExists(client: Client, databaseName: string) {
118 // Instead of checking for existence first, we just ignore a does not exist error so we don't have to query the DB all the time
119 try {
120 await setAllowConnections(client, databaseName, false).catch(() => void 0)
121
122 for (let attempt = 0; attempt < MAX_DROP_ATTEMPTS; attempt++) {
123 await cancelAndTerminateDatabaseConnections(client, databaseName)
124
125 try {
126 await client.query(
127 `DROP DATABASE IF EXISTS ${quoteIdentifier(databaseName)};`
128 )
129 return
130 } catch (error) {
131 const message = String((error as Error).message)
132
133 if (message.includes("does not exist")) {
134 return
135 }
136
137 if (
138 message.includes("being accessed by other users") &&
139 attempt < MAX_DROP_ATTEMPTS - 1
140 ) {
141 await sleep(50 * (attempt + 1))
142 continue
143 }
144
145 throw error
146 }
147 }
148 } catch (error) {
149 if (String((error as Error).message).includes("does not exist")) {
150 return
151 }
152
153 throw error
154 }
155 }
156
157 export async function createPostgresDatabaseTemplate({
158 databaseName,
159 templateName,
160 }: DatabaseTemplateOptions) {
161 if (databaseName === templateName) {
162 throw new Error("Template database name must differ from source database")
163 }
164
165 const client = await getWaitingroomClient()
166 await dropDatabaseIfExists(client, templateName)
167 await setAllowConnections(client, databaseName, false)
168 await terminateDatabaseConnections(client, databaseName)
169
170 try {
171 await client.query(
172 `CREATE DATABASE ${quoteIdentifier(
173 templateName
174 )} WITH TEMPLATE ${quoteIdentifier(databaseName)};`
175 )
176 } finally {
177 await setAllowConnections(client, databaseName, true)
178 }
179 }
180
181 export async function restorePostgresDatabaseFromTemplate({
182 databaseName,
183 templateName,
184 }: DatabaseTemplateOptions) {
185 if (databaseName === templateName) {
186 throw new Error("Template database name must differ from target database")
187 }
188
189 const client = await getWaitingroomClient()
190
191 await setAllowConnections(client, databaseName, false)
192 await dropDatabaseIfExists(client, databaseName)
193 await terminateDatabaseConnections(client, templateName)
194 await client.query(
195 `CREATE DATABASE ${quoteIdentifier(
196 databaseName
197 )} WITH TEMPLATE ${quoteIdentifier(templateName)};`
198 )
199 await setAllowConnections(client, databaseName, true)
200 }
201
202 export async function dropPostgresDatabaseTemplate(templateName: string) {
203 const client = await getWaitingroomClient()
204 await dropDatabaseIfExists(client, templateName)
205 }
206
207 // Postgres error codes — see https://www.postgresql.org/docs/current/errcodes-appendix.html
208 const DUPLICATE_DATABASE = "42P04" // database already exists
209 const INVALID_CATALOG_NAME = "3D000" // database does not exist
210
211 type DatabaseCredentials = {
212 user?: string
213 database?: string
214 password?: string
215 port?: number
216 host?: string
217 }
218
219 // Defaults mirror the previously used pg-god behavior: connect to the
220 // maintenance `postgres` database to create/drop another database.
221 const defaultDatabaseCredentials: Required<DatabaseCredentials> = {
222 user: "postgres",
223 database: "postgres",
224 password: "",
225 port: 5432,
226 host: "localhost",
227 }
228
229 /**
230 * Creates a database. When `errorIfExist` is false (the default), an already
231 * existing database is treated as success. Native replacement for the
232 * unmaintained `pg-god` `createDatabase`.
233 */
234 export async function createDatabase(
235 {
236 databaseName,
237 errorIfExist = false,
238 }: { databaseName: string; errorIfExist?: boolean },
239 credentials: DatabaseCredentials = {}
240 ): Promise<void> {
241 const client = new Client({ ...defaultDatabaseCredentials, ...credentials })
242
243 try {
244 await client.connect()
245 // `CREATE DATABASE` cannot be parameterized, and the name is always
246 // internally generated (never user supplied), so it is safely quoted and
247 // interpolated.
248 await client.query(`CREATE DATABASE ${quoteIdentifier(databaseName)};`)
249 } catch (error) {
250 if (
251 !errorIfExist &&
252 (error as { code?: string })?.code === DUPLICATE_DATABASE
253 ) {
254 return
255 }
256
257 throw error
258 } finally {
259 await client.end()
260 }
261 }
262
263 /**
264 * Drops a database. When `errorIfNonExist` is false (the default), a missing
265 * database is treated as success. Active connections to the database are
266 * terminated first unless `dropConnections` is set to false. Native
267 * replacement for the unmaintained `pg-god` `dropDatabase`.
268 */
269 export async function dropDatabase(
270 {
271 databaseName,
272 errorIfNonExist = false,
273 dropConnections = true,
274 }: {
275 databaseName: string
276 errorIfNonExist?: boolean
277 dropConnections?: boolean
278 },
279 credentials: DatabaseCredentials = {}
280 ): Promise<void> {
281 const client = new Client({ ...defaultDatabaseCredentials, ...credentials })
282
283 try {
284 await client.connect()
285
286 if (dropConnections) {
287 await terminateDatabaseConnections(client, databaseName)
288 }
289
290 await client.query(`DROP DATABASE ${quoteIdentifier(databaseName)};`)
291 } catch (error) {
292 if (
293 !errorIfNonExist &&
294 (error as { code?: string })?.code === INVALID_CATALOG_NAME
295 ) {
296 return
297 }
298
299 throw error
300 } finally {
301 await client.end()
302 }
303 }