database_upgrader.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import argparse
  2. import os
  3. import sqlite3
  4. import sys
  5. sys.path.append(os.path.dirname(os.path.dirname(__file__)))
  6. from timesearch_modules import tsdb
  7. def upgrade_1_to_2(db):
  8. '''
  9. In this version, many of the timesearch modules were renamed, including
  10. redmash -> index. This update will rename the existing `redmash` folder
  11. to `index`.
  12. '''
  13. cur = db.sql.cursor()
  14. redmash_dir = db.index_dir.parent.with_child('redmash')
  15. if redmash_dir.exists:
  16. redmash_dir.assert_is_directory()
  17. print('Renaming redmash folder to index.')
  18. os.rename(redmash_dir, db.index_dir)
  19. def upgrade_all(database_filename):
  20. '''
  21. Given the filename of a database, apply all of the needed
  22. upgrade_x_to_y functions in order.
  23. '''
  24. db = tsdb.TSDB(database_filename, do_create=False, skip_version_check=True)
  25. cur = db.sql.cursor()
  26. cur.execute('PRAGMA user_version')
  27. current_version = cur.fetchone()[0]
  28. needed_version = tsdb.DATABASE_VERSION
  29. if current_version == needed_version:
  30. print('Already up to date with version %d.' % needed_version)
  31. return
  32. for version_number in range(current_version + 1, needed_version + 1):
  33. print('Upgrading from %d to %d' % (current_version, version_number))
  34. upgrade_function = 'upgrade_%d_to_%d' % (current_version, version_number)
  35. upgrade_function = eval(upgrade_function)
  36. upgrade_function(db)
  37. db.sql.cursor().execute('PRAGMA user_version = %d' % version_number)
  38. db.sql.commit()
  39. current_version = version_number
  40. print('Upgrades finished.')
  41. def upgrade_all_argparse(args):
  42. return upgrade_all(database_filename=args.database_filename)
  43. def main(argv):
  44. parser = argparse.ArgumentParser()
  45. parser.add_argument('database_filename')
  46. parser.set_defaults(func=upgrade_all_argparse)
  47. args = parser.parse_args(argv)
  48. return args.func(args)
  49. if __name__ == '__main__':
  50. raise SystemExit(main(sys.argv[1:]))