backup.go 8.2 KB

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