Skip to content

Commit

Permalink
Fix migration that drops unique index (#384)
Browse files Browse the repository at this point in the history
  • Loading branch information
adamiak committed Apr 17, 2023
1 parent 820395e commit c040b4f
Showing 1 changed file with 25 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,38 @@ should create a new migration file that fixes the issue.
import { Knex } from 'knex'

export async function up(knex: Knex) {
const uniqueIndexName =
'preprocessed_asset_history_stark_key_asset_hash_or_id_unique'
const indexExists = await pgCheckIfIndexExists(knex, uniqueIndexName)
if (!indexExists) {
// This migration was already run, so we can safely
// return without doing anything. This is because the down()
// migration is not possible to run - see the comment there.
return
}

await knex.schema.table('preprocessed_asset_history', (table) => {
table.dropIndex(
[],
'preprocessed_asset_history_stark_key_asset_hash_or_id_unique'
)
table.dropIndex([], uniqueIndexName)

table.index(['stark_key', 'asset_hash_or_id'], undefined, {
predicate: knex.whereRaw('is_current = true'),
})
})
}

export async function down(knex: Knex) {
await knex.schema.table('preprocessed_asset_history', (table) => {
table.dropIndex(
[],
'preprocessed_asset_history_stark_key_asset_hash_or_id_index'
)
export async function down() {
// Not possible to re-add unique index (duplicates in the table),
}

table.unique(['stark_key', 'asset_hash_or_id'], {
predicate: knex.whereRaw('is_current = true'),
})
})
async function pgCheckIfIndexExists(
knex: Knex,
indexName: string
): Promise<boolean> {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const result = await knex.raw(
"SELECT * FROM pg_indexes WHERE indexname = ? AND schemaname = 'public'",
[indexName]
)
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return result.rows.length > 0
}

0 comments on commit c040b4f

Please sign in to comment.