1 /*
2 |--------------------------------------------------------------------------
3 | PostgreSQL utilities
4 |--------------------------------------------------------------------------
5 |
6 | @note
7 | These utlities does not rely on an MedusaJS application and neither
8 | uses the Mikro ORM.
9 | The goal here is to run DB operations without booting the application.
10 |
11 | For example:
12 | Creating a database from CLI, or checking if a database exists
13 |
14 */
15
16 import { Client, type ClientConfig } from "@medusajs/deps/pg"
17 import { parse } from "pg-connection-string"
18
19 /**
20 * Parsers the database connection string into an object
21 * of postgreSQL options
22 */
23 export function parseConnectionString(connectionString: string) {
24 return parse(connectionString)
25 }
26
27 /**
28 * Creates a PostgreSQL database client using the connection
29 * string or database options
30 */
31 export function createClient(options: string | ClientConfig) {
32 return new Client(options)
33 }
34
35 /**
36 * Creates a database using the client. Make sure to call
37 * `client.connect` before using this utility.
38 */
39 export async function createDb(client: Client, databaseName: string) {
40 await client.query(`CREATE DATABASE "${databaseName}"`)
41 }
42
43 /**
44 * Checks if a database exists using the Client. Make sure to call
45 * `client.connect` before using this utility.
46 */
47 export async function dbExists(client: Client, databaseName: string) {
48 const result = await client.query(
49 `SELECT datname FROM pg_catalog.pg_database WHERE datname='${databaseName}';`
50 )
51 return !!result.rowCount
52 }