1 import { EOL } from "os"
2 import type pg from "@medusajs/deps/pg"
3 import postgresClient, {
4 DEFAULT_HOST,
5 DEFAULT_PORT,
6 } from "./postgres-client.js"
7 import inquirer from "inquirer"
8 import logMessage from "./log-message.js"
9 import formatConnectionString from "./format-connection-string.js"
10 import { Ora } from "ora"
11 import { getCurrentOs } from "./get-current-os.js"
12 import terminalLink from "terminal-link"
13
14 type CreateDbOptions = {
15 client: pg.Client
16 db: string
17 }
18
19 export default async function createDb({ client, db }: CreateDbOptions) {
20 await client.query(`CREATE DATABASE "${db}"`)
21 }
22
23 async function doesDbExist(
24 client: pg.Client,
25 dbName: string
26 ): Promise<boolean> {
27 const result = await client.query(
28 `SELECT datname FROM pg_catalog.pg_database WHERE datname='${dbName}';`
29 )
30
31 return !!result.rowCount
32 }
33
34 export async function runCreateDb({
35 client,
36 dbName,
37 spinner,
38 }: {
39 client: pg.Client
40 dbName: string
41 spinner: Ora
42 }): Promise<pg.Client> {
43 let newClient = client
44
45 try {
46 // create postgres database
47 await createDb({
48 client,
49 db: dbName,
50 })
51
52 // create a new connection with database selected
53 await client.end()
54 newClient = await postgresClient({
55 user: client.user,
56 password: client.password,
57 database: dbName,
58 })
59 } catch (e) {
60 spinner.stop()
61 logMessage({
62 message: `An error occurred while trying to create your database: ${e}`,
63 type: "error",
64 })
65 }
66
67 return newClient
68 }
69
70 /**
71 * Connects to the server's `postgres` maintenance database, falling back to the
72 * connection's default database (which Postgres resolves to the username).
73 */
74 async function connectToMaintenanceDb(
75 connection: Parameters<typeof postgresClient>[0]
76 ): Promise<pg.Client> {
77 try {
78 return await postgresClient({
79 ...connection,
80 database: "postgres",
81 })
82 } catch (e) {
83 return await postgresClient(connection)
84 }
85 }
86
87 async function getForDbName({
88 dbName,
89 verbose = false,
90 }: {
91 dbName: string
92 verbose?: boolean
93 }): Promise<{
94 client: pg.Client
95 dbConnectionString: string
96 dbName: string
97 }> {
98 let client!: pg.Client
99 let postgresUsername = "postgres"
100 let postgresPassword = ""
101
102 const defaultConnectionOptions = {
103 host: DEFAULT_HOST,
104 port: DEFAULT_PORT,
105 }
106
107 try {
108 client = await postgresClient({
109 user: postgresUsername,
110 password: postgresPassword,
111 ...defaultConnectionOptions,
112 })
113 } catch (e) {
114 if (verbose) {
115 logMessage({
116 message: `The following error occurred when connecting to the database: ${e}`,
117 type: "verbose",
118 })
119 }
120 logMessage({
121 message: `${EOL}Couldn't connect to PostgreSQL with the default credentials (user "postgres" without a password).${EOL}Medusa needs to connect to your PostgreSQL server to create the database of your project, so please enter your PostgreSQL credentials below.${EOL}`,
122 })
123
124 // ask for the user's postgres credentials
125 const answers = await inquirer.prompt([
126 {
127 type: "input",
128 name: "postgresUsername",
129 message: "Enter your Postgres username",
130 default: "postgres",
131 validate: (input) => {
132 return typeof input === "string" && input.length > 0
133 },
134 },
135 {
136 type: "password",
137 name: "postgresPassword",
138 message: "Enter your Postgres password",
139 },
140 {
141 type: "input",
142 name: "newDbName",
143 message:
144 "Enter the name of the database to create for your Medusa project",
145 default: dbName,
146 validate: (input) => {
147 return typeof input === "string" && input.length > 0
148 },
149 },
150 ])
151
152 postgresUsername = answers.postgresUsername
153 postgresPassword = answers.postgresPassword
154 dbName = answers.newDbName
155
156 try {
157 client = await connectToMaintenanceDb({
158 user: postgresUsername,
159 password: postgresPassword,
160 ...defaultConnectionOptions,
161 })
162 } catch (e) {
163 logMessage({
164 message: `Couldn't connect to PostgreSQL because of the following error: ${e}.${EOL}${EOL}Make sure you have PostgreSQL installed and the credentials you provided are correct.${EOL}${EOL}If you keep running into this issue despite having PostgreSQL installed, please check out our ${terminalLink(
165 "troubleshooting guides",
166 "https://docs.medusajs.com/resources/troubleshooting/database-errors"
167 )}.`,
168 type: "error",
169 })
170 }
171 }
172
173 // check if database exists
174 if (await doesDbExist(client, dbName)) {
175 const { newDbName } = await inquirer.prompt([
176 {
177 type: "input",
178 name: "newDbName",
179 message: `A database already exists with the name ${dbName}, please enter a name for the database:`,
180 default: dbName,
181 validate: (input) => {
182 return (
183 typeof input === "string" && input.length > 0 && input !== dbName
184 )
185 },
186 },
187 ])
188
189 dbName = newDbName
190 }
191
192 // format connection string
193 const dbConnectionString = formatConnectionString({
194 user: postgresUsername,
195 password: postgresPassword,
196 host: client!.host,
197 db: dbName,
198 })
199
200 return {
201 client,
202 dbConnectionString,
203 dbName,
204 }
205 }
206
207 async function getForDbUrl({
208 dbUrl,
209 verbose = false,
210 }: {
211 dbUrl: string
212 verbose?: boolean
213 }): Promise<{
214 client: pg.Client
215 dbConnectionString: string
216 }> {
217 let client!: pg.Client
218
219 try {
220 client = await postgresClient({
221 connectionString: dbUrl,
222 })
223 } catch (e) {
224 if (verbose) {
225 logMessage({
226 message: `The following error occurred when connecting to the database: ${e}`,
227 type: "verbose",
228 })
229 }
230 logMessage({
231 message: `Couldn't connect to PostgreSQL using the database URL you passed. Make sure it's correct and try again.`,
232 type: "error",
233 })
234 }
235
236 return {
237 client,
238 dbConnectionString: dbUrl,
239 }
240 }
241
242 export async function getDbClientAndCredentials({
243 dbName = "",
244 dbUrl = "",
245 verbose = false,
246 }): Promise<{
247 client: pg.Client
248 dbConnectionString: string
249 verbose?: boolean
250 dbName?: string
251 }> {
252 // Check the db-url first, because the dbName is always defined in MedusaProjectCreator->create()->initializeProject()->setupDatabase()
253 if (dbUrl) {
254 return await getForDbUrl({
255 dbUrl,
256 verbose,
257 })
258 } else {
259 return await getForDbName({
260 dbName,
261 verbose,
262 })
263 }
264 }