Skip to content

Check schema when checking for migrations table. #34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 21 additions & 9 deletions src/migrate.ts
Original file line number Diff line number Diff line change
@@ -69,11 +69,13 @@ function runMigrations(intendedMigrations: Array<Migration>, 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<Migration>, 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<Migration>, 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
}