Migration Error - tokenVersion missing column - Fix

If you are using Botpress <= 12.18.2 and have experienced an issue where you got error messages complaining about a missing database table column named tokenVersion, I have come up with 2 different solutions.

Solution 1: hook
You will need to add the missing tokenVersion to relevant tables. This can be achieved by using a after_server_start hook. Copy-paste this in a new after_server_start hook from your Botpress Code Editor:

function hook(bp: typeof sdk) {
  /** Your code starts below */

  const log = msg => {
    bp.logger.info(`[tokenVersion] ${msg}`)
  }

  const COLUMN_NAME = 'tokenVersion'

  const myHook = async () => {
    log('Starting migration')

    const config = await bp.config.getBotpressConfig()

    const strategies = Object.keys(config.authStrategies)
    log(`Found strategies: ${strategies}`)

    for (const strategy of strategies) {
      const tableName = `strategy_${strategy}`

      if (!(await bp.database.schema.hasTable(tableName))) {
        log(`Table ${tableName} does not exist, continuing ...`)
        continue
      }

      if (await bp.database.schema.hasColumn(tableName, COLUMN_NAME)) {
        log(`Table ${tableName} already has column ${COLUMN_NAME}, continuing ...`)
        continue
      }

      log(`Adding ${COLUMN_NAME} to table ${tableName}`)
      await bp.database.schema.alterTable(tableName, table => {
        table
          .integer(COLUMN_NAME)
          .notNullable()
          .defaultTo(1)
      })
      log(`Added ${COLUMN_NAME} to table ${tableName}`)
    }

    log('Migration completed')
  }

  return myHook()

  /** Your code ends here */
}

Then, restart your Botpress server to have the migration applied. Test again, and if the symptoms are gone, you can safely delete that hook.

Solution 2: Upgrade to Botpress 12.18.3
Simply upgrading your Botpress to 12.18.3 will automatically add the missing column. Relevant pull request can be found here: fix(migrations): proper migration for tokenVersion by spg · Pull Request #4690 · botpress/botpress · GitHub

1 Like