diff --git a/src/migrate.ts b/src/migrate.ts index b874f81..4cf5bf7 100644 --- a/src/migrate.ts +++ b/src/migrate.ts @@ -69,11 +69,13 @@ function runMigrations(intendedMigrations: Array, log: Logger) { return async (client: BasicPgClient) => { try { const migrationTableName = "migrations" + const schema = "public" log("Starting migrations") const appliedMigrations = await fetchAppliedMigrationFromDB( migrationTableName, + schema, client, log, ) @@ -115,12 +117,14 @@ function runMigrations(intendedMigrations: Array, log: Logger) { /** Queries the database for migrations table and retrieve it rows if exists */ async function fetchAppliedMigrationFromDB( migrationTableName: string, + schema: string, client: BasicPgClient, log: Logger, ) { let appliedMigrations = [] - if (await doesTableExist(client, migrationTableName)) { - log(`Migrations table with name '${migrationTableName}' exists, + if (await doesTableExist(client, migrationTableName, schema)) { + log(` +Migrations table with name '${migrationTableName}' exists, filtering not applied migrations.`) const {rows} = await client.query( @@ -189,13 +193,21 @@ function logResult(completedMigrations: Array, log: Logger) { } /** Check whether table exists in postgres - http://stackoverflow.com/a/24089729 */ -async function doesTableExist(client: BasicPgClient, tableName: string) { - const result = await client.query(SQL`SELECT EXISTS ( - SELECT 1 - FROM pg_catalog.pg_class c - WHERE c.relname = ${tableName} - AND c.relkind = 'r' -);`) +async function doesTableExist( + client: BasicPgClient, + tableName: string, + schema: string, +) { + const result = await client.query(SQL` + SELECT EXISTS ( + SELECT 1 + FROM pg_catalog.pg_class c + JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = ${schema} + AND c.relname = ${tableName} + AND c.relkind = 'r' + ); + `) return result.rows.length > 0 && result.rows[0].exists }