backup.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. package db
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "os"
  7. "path/filepath"
  8. "reflect"
  9. "strings"
  10. "github.com/jinzhu/gorm"
  11. jsoniter "github.com/json-iterator/go"
  12. "github.com/pkg/errors"
  13. log "unknwon.dev/clog/v2"
  14. "xorm.io/core"
  15. "xorm.io/xorm"
  16. "gogs.io/gogs/internal/conf"
  17. "gogs.io/gogs/internal/osutil"
  18. )
  19. // getTableType returns the type name of a table definition without package name,
  20. // e.g. *db.LFSObject -> LFSObject.
  21. func getTableType(t interface{}) string {
  22. return strings.TrimPrefix(fmt.Sprintf("%T", t), "*db.")
  23. }
  24. // DumpDatabase dumps all data from database to file system in JSON Lines format.
  25. func DumpDatabase(db *gorm.DB, dirPath string, verbose bool) error {
  26. err := os.MkdirAll(dirPath, os.ModePerm)
  27. if err != nil {
  28. return err
  29. }
  30. err = dumpLegacyTables(dirPath, verbose)
  31. if err != nil {
  32. return errors.Wrap(err, "dump legacy tables")
  33. }
  34. for _, table := range tables {
  35. tableName := getTableType(table)
  36. if verbose {
  37. log.Trace("Dumping table %q...", tableName)
  38. }
  39. err := func() error {
  40. tableFile := filepath.Join(dirPath, tableName+".json")
  41. f, err := os.Create(tableFile)
  42. if err != nil {
  43. return errors.Wrap(err, "create table file")
  44. }
  45. defer func() { _ = f.Close() }()
  46. return dumpTable(db, table, f)
  47. }()
  48. if err != nil {
  49. return errors.Wrapf(err, "dump table %q", tableName)
  50. }
  51. }
  52. return nil
  53. }
  54. func dumpTable(db *gorm.DB, table interface{}, w io.Writer) error {
  55. query := db.Model(table).Order("id ASC")
  56. switch table.(type) {
  57. case *LFSObject:
  58. query = db.Model(table).Order("repo_id, oid ASC")
  59. }
  60. rows, err := query.Rows()
  61. if err != nil {
  62. return errors.Wrap(err, "select rows")
  63. }
  64. defer func() { _ = rows.Close() }()
  65. for rows.Next() {
  66. elem := reflect.New(reflect.TypeOf(table).Elem()).Interface()
  67. err = db.ScanRows(rows, elem)
  68. if err != nil {
  69. return errors.Wrap(err, "scan rows")
  70. }
  71. err = jsoniter.NewEncoder(w).Encode(elem)
  72. if err != nil {
  73. return errors.Wrap(err, "encode JSON")
  74. }
  75. }
  76. return nil
  77. }
  78. func dumpLegacyTables(dirPath string, verbose bool) error {
  79. // Purposely create a local variable to not modify global variable
  80. legacyTables := append(legacyTables, new(Version))
  81. for _, table := range legacyTables {
  82. tableName := getTableType(table)
  83. if verbose {
  84. log.Trace("Dumping table %q...", tableName)
  85. }
  86. tableFile := filepath.Join(dirPath, tableName+".json")
  87. f, err := os.Create(tableFile)
  88. if err != nil {
  89. return fmt.Errorf("create JSON file: %v", err)
  90. }
  91. if err = x.Asc("id").Iterate(table, func(idx int, bean interface{}) (err error) {
  92. return jsoniter.NewEncoder(f).Encode(bean)
  93. }); err != nil {
  94. _ = f.Close()
  95. return fmt.Errorf("dump table '%s': %v", tableName, err)
  96. }
  97. _ = f.Close()
  98. }
  99. return nil
  100. }
  101. // ImportDatabase imports data from backup archive in JSON Lines format.
  102. func ImportDatabase(db *gorm.DB, dirPath string, verbose bool) error {
  103. err := importLegacyTables(dirPath, verbose)
  104. if err != nil {
  105. return errors.Wrap(err, "import legacy tables")
  106. }
  107. for _, table := range tables {
  108. tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*db.")
  109. err := func() error {
  110. tableFile := filepath.Join(dirPath, tableName+".json")
  111. if !osutil.IsFile(tableFile) {
  112. log.Info("Skipped table %q", tableName)
  113. return nil
  114. }
  115. if verbose {
  116. log.Trace("Importing table %q...", tableName)
  117. }
  118. f, err := os.Open(tableFile)
  119. if err != nil {
  120. return errors.Wrap(err, "open table file")
  121. }
  122. defer func() { _ = f.Close() }()
  123. return importTable(db, table, f)
  124. }()
  125. if err != nil {
  126. return errors.Wrapf(err, "import table %q", tableName)
  127. }
  128. }
  129. return nil
  130. }
  131. func importTable(db *gorm.DB, table interface{}, r io.Reader) error {
  132. err := db.DropTableIfExists(table).Error
  133. if err != nil {
  134. return errors.Wrap(err, "drop table")
  135. }
  136. err = db.AutoMigrate(table).Error
  137. if err != nil {
  138. return errors.Wrap(err, "auto migrate")
  139. }
  140. rawTableName := db.NewScope(table).TableName()
  141. skipResetIDSeq := map[string]bool{
  142. "lfs_object": true,
  143. }
  144. scanner := bufio.NewScanner(r)
  145. for scanner.Scan() {
  146. elem := reflect.New(reflect.TypeOf(table).Elem()).Interface()
  147. err = jsoniter.Unmarshal(scanner.Bytes(), elem)
  148. if err != nil {
  149. return errors.Wrap(err, "unmarshal JSON to struct")
  150. }
  151. err = db.Create(elem).Error
  152. if err != nil {
  153. return errors.Wrap(err, "create row")
  154. }
  155. }
  156. // PostgreSQL needs manually reset table sequence for auto increment keys
  157. if conf.UsePostgreSQL && !skipResetIDSeq[rawTableName] {
  158. seqName := rawTableName + "_id_seq"
  159. if _, err = x.Exec(fmt.Sprintf(`SELECT setval('%s', COALESCE((SELECT MAX(id)+1 FROM "%s"), 1), false);`, seqName, rawTableName)); err != nil {
  160. return errors.Wrapf(err, "reset table %q.%q", rawTableName, seqName)
  161. }
  162. }
  163. return nil
  164. }
  165. func importLegacyTables(dirPath string, verbose bool) error {
  166. snakeMapper := core.SnakeMapper{}
  167. skipInsertProcessors := map[string]bool{
  168. "mirror": true,
  169. "milestone": true,
  170. }
  171. // Purposely create a local variable to not modify global variable
  172. legacyTables := append(legacyTables, new(Version))
  173. for _, table := range legacyTables {
  174. tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*db.")
  175. tableFile := filepath.Join(dirPath, tableName+".json")
  176. if !osutil.IsFile(tableFile) {
  177. continue
  178. }
  179. if verbose {
  180. log.Trace("Importing table %q...", tableName)
  181. }
  182. if err := x.DropTables(table); err != nil {
  183. return fmt.Errorf("drop table %q: %v", tableName, err)
  184. } else if err = x.Sync2(table); err != nil {
  185. return fmt.Errorf("sync table %q: %v", tableName, err)
  186. }
  187. f, err := os.Open(tableFile)
  188. if err != nil {
  189. return fmt.Errorf("open JSON file: %v", err)
  190. }
  191. rawTableName := x.TableName(table)
  192. _, isInsertProcessor := table.(xorm.BeforeInsertProcessor)
  193. scanner := bufio.NewScanner(f)
  194. for scanner.Scan() {
  195. if err = jsoniter.Unmarshal(scanner.Bytes(), table); err != nil {
  196. return fmt.Errorf("unmarshal to struct: %v", err)
  197. }
  198. if _, err = x.Insert(table); err != nil {
  199. return fmt.Errorf("insert strcut: %v", err)
  200. }
  201. meta := make(map[string]interface{})
  202. if err = jsoniter.Unmarshal(scanner.Bytes(), &meta); err != nil {
  203. log.Error("Failed to unmarshal to map: %v", err)
  204. }
  205. // Reset created_unix back to the date save in archive because Insert method updates its value
  206. if isInsertProcessor && !skipInsertProcessors[rawTableName] {
  207. if _, err = x.Exec("UPDATE `"+rawTableName+"` SET created_unix=? WHERE id=?", meta["CreatedUnix"], meta["ID"]); err != nil {
  208. log.Error("Failed to reset 'created_unix': %v", err)
  209. }
  210. }
  211. switch rawTableName {
  212. case "milestone":
  213. if _, err = x.Exec("UPDATE `"+rawTableName+"` SET deadline_unix=?, closed_date_unix=? WHERE id=?", meta["DeadlineUnix"], meta["ClosedDateUnix"], meta["ID"]); err != nil {
  214. log.Error("Failed to reset 'milestone.deadline_unix', 'milestone.closed_date_unix': %v", err)
  215. }
  216. }
  217. }
  218. // PostgreSQL needs manually reset table sequence for auto increment keys
  219. if conf.UsePostgreSQL {
  220. rawTableName := snakeMapper.Obj2Table(tableName)
  221. seqName := rawTableName + "_id_seq"
  222. if _, err = x.Exec(fmt.Sprintf(`SELECT setval('%s', COALESCE((SELECT MAX(id)+1 FROM "%s"), 1), false);`, seqName, rawTableName)); err != nil {
  223. return fmt.Errorf("reset table %q' sequence: %v", rawTableName, err)
  224. }
  225. }
  226. }
  227. return nil
  228. }