From 673276158f890ac1cc1b936df3124a0db578fd7d Mon Sep 17 00:00:00 2001 From: Dirk de Visser Date: Thu, 21 Sep 2023 23:17:18 +0200 Subject: [PATCH] feat(store): support specifying a maintenance database when using 'createIfNotExists' --- packages/store/src/postgres.js | 11 ++++++++++- packages/store/src/testing.js | 3 +++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/store/src/postgres.js b/packages/store/src/postgres.js index 57384ae6eb..a6ef2f3ab9 100644 --- a/packages/store/src/postgres.js +++ b/packages/store/src/postgres.js @@ -66,10 +66,16 @@ export function buildAndCheckOpts(opts) { * 'date' and 'time' columns, used by `T.date().timeOnly()` and `T.date().dateOnly()', as * strings. * + * With `createIfNotExists`, Compas will try to connect to Postgres and first check if + * the database exists before establishing the requested connection. Postgres will + * default to connect to a database with the same name as the provided user, but you can + * manually specify the 'maintenanceDatabase' for the temporary connection. + * * @since 0.1.0 * * @param {import("postgres").Options & { * createIfNotExists?: boolean, + * maintenanceDatabaase?: string, * }} [opts] * @returns {Promise>} */ @@ -80,6 +86,7 @@ export async function newPostgresConnection(opts) { const oldConnection = await createDatabaseIfNotExists( undefined, connectionOpts.database, + opts.maintenanceDatabaase, undefined, connectionOpts, ); @@ -92,6 +99,7 @@ export async function newPostgresConnection(opts) { /** * @param sql * @param databaseName + * @param maintenanceDatabase * @param template * @param connectionOptions * @returns {Promise>} @@ -99,6 +107,7 @@ export async function newPostgresConnection(opts) { export async function createDatabaseIfNotExists( sql, databaseName, + maintenanceDatabase, template, connectionOptions, ) { @@ -111,7 +120,7 @@ export async function createDatabaseIfNotExists( // Don't connect to a database const opts = { ...connectionOptions, - database: undefined, + database: maintenanceDatabase ?? undefined, }; if (!sql) { sql = postgres(environment.POSTGRES_URI ?? opts, opts); diff --git a/packages/store/src/testing.js b/packages/store/src/testing.js index ac8b8c2088..3bffd4915c 100644 --- a/packages/store/src/testing.js +++ b/packages/store/src/testing.js @@ -82,6 +82,7 @@ export async function createTestPostgresDatabase(rawOpts, options = {}) { const creationSql = await createDatabaseIfNotExists( undefined, name, + undefined, testDatabase?.options?.database, connectionOptions, ); @@ -104,6 +105,7 @@ export async function createTestPostgresDatabase(rawOpts, options = {}) { undefined, connectionOptions.database, undefined, + undefined, connectionOptions, ); @@ -123,6 +125,7 @@ export async function createTestPostgresDatabase(rawOpts, options = {}) { await createDatabaseIfNotExists( creationSql, name, + undefined, connectionOptions.database, connectionOptions, );