From 5f3ed07fd2e093d66f4f82dbfeb683b646cc1545 Mon Sep 17 00:00:00 2001 From: Remi Koenig Date: Fri, 3 Jan 2020 18:37:27 +0100 Subject: [PATCH] Check table exists in current search path * If a `migrations` table did exist in a schema outside of the search path, `doesTableExist` would return true but the migration would then fail with 'relation "migrations" does not exist' * See https://dba.stackexchange.com/a/86098 for the details on the query * This new query makes it possible to have one `migrations` table per schema --- src/migrate.ts | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/migrate.ts b/src/migrate.ts index b874f81..37a3e80 100644 --- a/src/migrate.ts +++ b/src/migrate.ts @@ -188,14 +188,13 @@ function logResult(completedMigrations: Array, log: Logger) { } } -/** Check whether table exists in postgres - http://stackoverflow.com/a/24089729 */ +/** Check whether table exists in postgres in the current search path + * http://stackoverflow.com/a/24089729 + * https://dba.stackexchange.com/a/86098 + */ 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' -);`) - + const result = await client.query( + SQL`SELECT to_regclass(${tableName}) is not NULL as exists;`, + ) return result.rows.length > 0 && result.rows[0].exists }