* Creates a new database if it does not exist.
(options: { env?: string; schema?: string } = {})
| 251 | * Creates a new database if it does not exist. |
| 252 | */ |
| 253 | async function createDatabase(options: { env?: string; schema?: string } = {}) { |
| 254 | let db = getDatabase(options); |
| 255 | const dbName = process.env.PGDATABASE; |
| 256 | const pgUser = process.env.PGUSER; |
| 257 | |
| 258 | if (!dbName) throw new Error("PGDATABASE is not set"); |
| 259 | if (!pgUser) throw new Error("PGUSER is not set"); |
| 260 | |
| 261 | try { |
| 262 | await db.select(db.raw("current_database()")); |
| 263 | } catch (err) { |
| 264 | // Error code 3D000 indicates that the database does not exist. |
| 265 | if ((err as NodeJS.ErrnoException).code !== "3D000") { |
| 266 | throw err; |
| 267 | } |
| 268 | |
| 269 | await db.destroy(); |
| 270 | |
| 271 | process.env.PGDATABASE = "template1"; |
| 272 | |
| 273 | db = getDatabase(options); |
| 274 | |
| 275 | // Attempt to create a new database. |
| 276 | await db.raw(`CREATE DATABASE ?? WITH OWNER ??`, [dbName, pgUser]); |
| 277 | |
| 278 | // Attempt to create a new database schema. |
| 279 | await db.raw(`CREATE SCHEMA IF NOT EXISTS ?? AUTHORIZATION ??`, [ |
| 280 | options?.schema, |
| 281 | pgUser, |
| 282 | ]); |
| 283 | } finally { |
| 284 | process.env.PGDATABASE = dbName; |
| 285 | await db.destroy(); |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | /** |
| 290 | * Launches an interactive terminal with Knex.js. |