restore.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import { pgRestore } from 'pg-dump-restore'
  2. import { promises as fs } from 'fs'
  3. import path from 'path'
  4. import { logger } from './logger'
  5. import process from 'node:process'
  6. const BACKUP_DIR = process.env.BACKUP_DIR || './backups'
  7. export interface RestoreOptions {
  8. host?: string
  9. port?: number
  10. database?: string
  11. username?: string
  12. password?: string
  13. backupFile?: string
  14. }
  15. export class DatabaseRestore {
  16. private getDbConfig() {
  17. return {
  18. host: process.env.DB_HOST || 'localhost',
  19. port: parseInt(process.env.DB_PORT || '5432'),
  20. database: process.env.DB_DATABASE || 'postgres',
  21. username: process.env.DB_USERNAME || 'postgres',
  22. password: process.env.DB_PASSWORD || '',
  23. }
  24. }
  25. async restoreDatabase(options: Partial<RestoreOptions> = {}): Promise<void> {
  26. const config = { ...this.getDbConfig(), ...options }
  27. let backupFile = options.backupFile
  28. if (!backupFile) {
  29. const latestBackup = await this.findLatestBackup()
  30. if (!latestBackup) {
  31. throw new Error('未找到可用的备份文件')
  32. }
  33. backupFile = latestBackup
  34. }
  35. if (!await this.backupExists(backupFile)) {
  36. throw new Error(`备份文件不存在: ${backupFile}`)
  37. }
  38. try {
  39. logger.db(`开始恢复数据库备份: ${backupFile}`)
  40. await pgRestore({
  41. host: config.host,
  42. port: config.port,
  43. database: config.database,
  44. username: config.username,
  45. password: config.password,
  46. }, {
  47. filePath: backupFile,
  48. clean: true,
  49. ifExists: true
  50. })
  51. logger.db(`数据库恢复成功: ${config.database}`)
  52. } catch (error) {
  53. logger.error(`数据库恢复失败: ${error}`)
  54. throw error
  55. }
  56. }
  57. async findLatestBackup(): Promise<string | null> {
  58. try {
  59. const files = await fs.readdir(BACKUP_DIR)
  60. const backupFiles = files
  61. .filter(f => f.endsWith('.dump'))
  62. .sort()
  63. .reverse()
  64. return backupFiles.length > 0 ? path.join(BACKUP_DIR, backupFiles[0]) : null
  65. } catch (error) {
  66. logger.error(`查找备份文件失败: ${error}`)
  67. return null
  68. }
  69. }
  70. async listBackups(): Promise<string[]> {
  71. try {
  72. const files = await fs.readdir(BACKUP_DIR)
  73. return files.filter(f => f.endsWith('.dump'))
  74. } catch (error) {
  75. logger.error(`列出备份文件失败: ${error}`)
  76. return []
  77. }
  78. }
  79. async backupExists(backupFile: string): Promise<boolean> {
  80. try {
  81. await fs.access(backupFile)
  82. return true
  83. } catch {
  84. return false
  85. }
  86. }
  87. async getBackupInfo(backupFile: string): Promise<{
  88. size: number
  89. mtime: Date
  90. formattedSize: string
  91. }> {
  92. try {
  93. const stats = await fs.stat(backupFile)
  94. return {
  95. size: stats.size,
  96. mtime: stats.mtime,
  97. formattedSize: this.formatFileSize(stats.size)
  98. }
  99. } catch (error) {
  100. throw new Error(`获取备份信息失败: ${error}`)
  101. }
  102. }
  103. private formatFileSize(bytes: number): string {
  104. const sizes = ['B', 'KB', 'MB', 'GB']
  105. if (bytes === 0) return '0 B'
  106. const i = Math.floor(Math.log(bytes) / Math.log(1024))
  107. return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]
  108. }
  109. }
  110. export const databaseRestore = new DatabaseRestore()
  111. if (import.meta.url === `file://${process.argv[1]}`) {
  112. async function main() {
  113. const command = process.argv[2]
  114. const restoreTool = new DatabaseRestore()
  115. switch (command) {
  116. case 'restore':
  117. const backupFile = process.argv[3]
  118. await restoreTool.restoreDatabase({ backupFile })
  119. break
  120. case 'list':
  121. const backups = await restoreTool.listBackups()
  122. console.log('可用备份文件:')
  123. backups.forEach(file => console.log(` - ${file}`))
  124. break
  125. case 'latest':
  126. const latest = await restoreTool.findLatestBackup()
  127. if (latest) {
  128. console.log(`最新备份文件: ${latest}`)
  129. const info = await restoreTool.getBackupInfo(latest)
  130. console.log(`文件大小: ${info.formattedSize}`)
  131. console.log(`修改时间: ${info.mtime}`)
  132. } else {
  133. console.log('未找到备份文件')
  134. }
  135. break
  136. default:
  137. console.log('用法: node restore.ts [restore <file>|list|latest]')
  138. console.log(' restore <file> - 恢复指定备份文件')
  139. console.log(' list - 列出所有备份文件')
  140. console.log(' latest - 显示最新备份文件信息')
  141. process.exit(1)
  142. }
  143. }
  144. main().catch(console.error)
  145. }