sqlite.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. import logging
  2. import os
  3. from borgmatic.execute import execute_command, execute_command_with_processes
  4. from borgmatic.hooks import dump
  5. logger = logging.getLogger(__name__)
  6. def make_dump_path(location_config): # pragma: no cover
  7. '''
  8. Make the dump path from the given location configuration and the name of this hook.
  9. '''
  10. return dump.make_database_dump_path(
  11. location_config.get('borgmatic_source_directory'), 'sqlite_databases'
  12. )
  13. def dump_databases(databases, log_prefix, location_config, dry_run):
  14. '''
  15. Dump the given SQLite3 databases to a file. The databases are supplied as a sequence of
  16. configuration dicts, as per the configuration schema. Use the given log prefix in any log
  17. entries. Use the given location configuration dict to construct the destination path. If this
  18. is a dry run, then don't actually dump anything.
  19. '''
  20. dry_run_label = ' (dry run; not actually dumping anything)' if dry_run else ''
  21. processes = []
  22. logger.info(f'{log_prefix}: Dumping SQLite databases{dry_run_label}')
  23. for database in databases:
  24. database_path = database['path']
  25. if database['name'] == 'all':
  26. logger.warning('The "all" database name has no meaning for SQLite3 databases')
  27. if not os.path.exists(database_path):
  28. logger.warning(
  29. f'{log_prefix}: No SQLite database at {database_path}; An empty database will be created and dumped'
  30. )
  31. dump_path = make_dump_path(location_config)
  32. dump_filename = dump.make_database_dump_filename(dump_path, database['name'])
  33. if os.path.exists(dump_filename):
  34. logger.warning(
  35. f'{log_prefix}: Skipping duplicate dump of SQLite database at {database_path} to {dump_filename}'
  36. )
  37. continue
  38. command = (
  39. 'sqlite3',
  40. database_path,
  41. '.dump',
  42. '>',
  43. dump_filename,
  44. )
  45. logger.debug(
  46. f'{log_prefix}: Dumping SQLite database at {database_path} to {dump_filename}{dry_run_label}'
  47. )
  48. if dry_run:
  49. continue
  50. dump.create_parent_directory_for_dump(dump_filename)
  51. processes.append(execute_command(command, shell=True, run_to_completion=False))
  52. return processes
  53. def remove_database_dumps(databases, log_prefix, location_config, dry_run): # pragma: no cover
  54. '''
  55. Remove the given SQLite3 database dumps from the filesystem. The databases are supplied as a
  56. sequence of configuration dicts, as per the configuration schema. Use the given log prefix in
  57. any log entries. Use the given location configuration dict to construct the destination path.
  58. If this is a dry run, then don't actually remove anything.
  59. '''
  60. dump.remove_database_dumps(make_dump_path(location_config), 'SQLite', log_prefix, dry_run)
  61. def make_database_dump_pattern(
  62. databases, log_prefix, location_config, name=None
  63. ): # pragma: no cover
  64. '''
  65. Make a pattern that matches the given SQLite3 databases. The databases are supplied as a
  66. sequence of configuration dicts, as per the configuration schema.
  67. '''
  68. return dump.make_database_dump_filename(make_dump_path(location_config), name)
  69. def restore_database_dump(database_config, log_prefix, location_config, dry_run, extract_process):
  70. '''
  71. Restore the given SQLite3 database from an extract stream. The database is supplied as a
  72. one-element sequence containing a dict describing the database, as per the configuration schema.
  73. Use the given log prefix in any log entries. If this is a dry run, then don't actually restore
  74. anything. Trigger the given active extract process (an instance of subprocess.Popen) to produce
  75. output to consume.
  76. '''
  77. dry_run_label = ' (dry run; not actually restoring anything)' if dry_run else ''
  78. if len(database_config) != 1:
  79. raise ValueError('The database configuration value is invalid')
  80. database_path = database_config[0]['path']
  81. logger.debug(f'{log_prefix}: Restoring SQLite database at {database_path}{dry_run_label}')
  82. if dry_run:
  83. return
  84. try:
  85. os.remove(database_path)
  86. logger.warning(f'{log_prefix}: Removed existing SQLite database at {database_path}')
  87. except FileNotFoundError: # pragma: no cover
  88. pass
  89. restore_command = (
  90. 'sqlite3',
  91. database_path,
  92. )
  93. # Don't give Borg local path so as to error on warnings, as "borg extract" only gives a warning
  94. # if the restore paths don't exist in the archive.
  95. execute_command_with_processes(
  96. restore_command,
  97. [extract_process],
  98. output_log_level=logging.DEBUG,
  99. input_file=extract_process.stdout,
  100. )