Skip to content

Commit

Permalink
feat(store): support specifying a maintenance database when using 'cr…
Browse files Browse the repository at this point in the history
…eateIfNotExists'
  • Loading branch information
dirkdev98 committed Sep 21, 2023
1 parent 97b7977 commit 6732761
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
11 changes: 10 additions & 1 deletion packages/store/src/postgres.js
Original file line number Diff line number Diff line change
Expand Up @@ -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<import("postgres").Sql<{}>>}
*/
Expand All @@ -80,6 +86,7 @@ export async function newPostgresConnection(opts) {
const oldConnection = await createDatabaseIfNotExists(
undefined,
connectionOpts.database,
opts.maintenanceDatabaase,
undefined,
connectionOpts,
);
Expand All @@ -92,13 +99,15 @@ export async function newPostgresConnection(opts) {
/**
* @param sql
* @param databaseName
* @param maintenanceDatabase
* @param template
* @param connectionOptions
* @returns {Promise<import("postgres").Sql<{}>>}
*/
export async function createDatabaseIfNotExists(
sql,
databaseName,
maintenanceDatabase,
template,
connectionOptions,
) {
Expand All @@ -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);
Expand Down
3 changes: 3 additions & 0 deletions packages/store/src/testing.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export async function createTestPostgresDatabase(rawOpts, options = {}) {
const creationSql = await createDatabaseIfNotExists(
undefined,
name,
undefined,
testDatabase?.options?.database,
connectionOptions,
);
Expand All @@ -104,6 +105,7 @@ export async function createTestPostgresDatabase(rawOpts, options = {}) {
undefined,
connectionOptions.database,
undefined,
undefined,
connectionOptions,
);

Expand All @@ -123,6 +125,7 @@ export async function createTestPostgresDatabase(rawOpts, options = {}) {
await createDatabaseIfNotExists(
creationSql,
name,
undefined,
connectionOptions.database,
connectionOptions,
);
Expand Down

0 comments on commit 6732761

Please sign in to comment.