11import * as pg from "pg"
22import SQL from "sql-template-strings"
3+ import { runCreateQuery } from "./create"
34import { loadMigrationFiles } from "./files-loader"
45import { runMigration } from "./run-migration"
56import {
@@ -14,6 +15,17 @@ import {validateMigrationHashes} from "./validation"
1415import { withConnection } from "./with-connection"
1516import { withAdvisoryLock } from "./with-lock"
1617
18+ /**
19+ * Run the migrations.
20+ *
21+ * If `dbConfig.ensureDatabaseExists` is true then `dbConfig.database` will be created if it
22+ * does not exist.
23+ *
24+ * @param dbConfig Details about how to connect to the database
25+ * @param migrationsDirectory Directory containing the SQL migration files
26+ * @param config Extra configuration
27+ * @returns Details about the migrations which were run
28+ */
1729export async function migrate (
1830 dbConfig : MigrateDBConfig ,
1931 migrationsDirectory : string ,
@@ -53,17 +65,45 @@ export async function migrate(
5365 throw new Error ( "Database config problem" )
5466 }
5567
56- const client = new pg . Client ( dbConfig )
57- client . on ( "error" , ( err ) => {
58- log ( `pg client emitted an error: ${ err . message } ` )
59- } )
68+ if ( dbConfig . ensureDatabaseExists === true ) {
69+ // Check whether database exists
70+ const { user, password, host, port} = dbConfig
71+ const client = new pg . Client ( {
72+ database :
73+ dbConfig . defaultDatabase != null
74+ ? dbConfig . defaultDatabase
75+ : "postgres" ,
76+ user,
77+ password,
78+ host,
79+ port,
80+ } )
81+
82+ const runWith = withConnection ( log , async ( connectedClient ) => {
83+ const result = await connectedClient . query ( {
84+ text : "SELECT 1 FROM pg_database WHERE datname=$1" ,
85+ values : [ dbConfig . database ] ,
86+ } )
87+ if ( result . rowCount !== 1 ) {
88+ await runCreateQuery ( dbConfig . database , log ) ( connectedClient )
89+ }
90+ } )
91+
92+ await runWith ( client )
93+ }
94+ {
95+ const client = new pg . Client ( dbConfig )
96+ client . on ( "error" , ( err ) => {
97+ log ( `pg client emitted an error: ${ err . message } ` )
98+ } )
6099
61- const runWith = withConnection (
62- log ,
63- withAdvisoryLock ( log , runMigrations ( intendedMigrations , log ) ) ,
64- )
100+ const runWith = withConnection (
101+ log ,
102+ withAdvisoryLock ( log , runMigrations ( intendedMigrations , log ) ) ,
103+ )
65104
66- return runWith ( client )
105+ return runWith ( client )
106+ }
67107}
68108
69109function runMigrations ( intendedMigrations : Array < Migration > , log : Logger ) {
0 commit comments