sqlite.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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(config): # pragma: no cover
  7. '''
  8. Make the dump path from the given configuration dict and the name of this hook.
  9. '''
  10. return dump.make_database_dump_path(
  11. config.get('borgmatic_source_directory'), 'sqlite_databases'
  12. )
  13. def dump_databases(databases, config, log_prefix, 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 configuration dict to
  17. construct the destination path and the given log prefix in any log entries. If this is a dry
  18. 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(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, config, log_prefix, 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 configuration
  57. dict to construct the destination path and the given log prefix in any log entries. If this is a
  58. dry run, then don't actually remove anything.
  59. '''
  60. dump.remove_database_dumps(make_dump_path(config), 'SQLite', log_prefix, dry_run)
  61. def make_database_dump_pattern(databases, config, log_prefix, name=None): # pragma: no cover
  62. '''
  63. Make a pattern that matches the given SQLite3 databases. The databases are supplied as a
  64. sequence of configuration dicts, as per the configuration schema.
  65. '''
  66. return dump.make_database_dump_filename(make_dump_path(config), name)
  67. def restore_database_dump(
  68. databases_config, config, log_prefix, database_name, dry_run, extract_process, connection_params
  69. ):
  70. '''
  71. Restore the given SQLite3 database from an extract stream. The databases are supplied as a
  72. sequence containing one dict describing each database (as per the configuration schema), but
  73. only the database corresponding to the given database name is restored. Use the given log prefix
  74. in any log entries. If this is a dry run, then don't actually restore anything. Trigger the
  75. given active extract process (an instance of subprocess.Popen) to produce output to consume.
  76. '''
  77. dry_run_label = ' (dry run; not actually restoring anything)' if dry_run else ''
  78. try:
  79. database = next(
  80. database_config
  81. for database_config in databases_config
  82. if database_config.get('name') == database_name
  83. )
  84. except StopIteration:
  85. raise ValueError(
  86. f'A database named "{database_name}" could not be found in the configuration'
  87. )
  88. database_path = connection_params['restore_path'] or database.get(
  89. 'restore_path', database.get('path')
  90. )
  91. logger.debug(f'{log_prefix}: Restoring SQLite database at {database_path}{dry_run_label}')
  92. if dry_run:
  93. return
  94. try:
  95. os.remove(database_path)
  96. logger.warning(f'{log_prefix}: Removed existing SQLite database at {database_path}')
  97. except FileNotFoundError: # pragma: no cover
  98. pass
  99. restore_command = (
  100. 'sqlite3',
  101. database_path,
  102. )
  103. # Don't give Borg local path so as to error on warnings, as "borg extract" only gives a warning
  104. # if the restore paths don't exist in the archive.
  105. execute_command_with_processes(
  106. restore_command,
  107. [extract_process],
  108. output_log_level=logging.DEBUG,
  109. input_file=extract_process.stdout,
  110. )