You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.0 KiB

  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "fmt"
  7. "time"
  8. "gopkg.in/testfixtures.v2"
  9. "xorm.io/xorm/schemas"
  10. )
  11. var fixtures *testfixtures.Context
  12. // InitFixtures initialize test fixtures for a test database
  13. func InitFixtures(helper testfixtures.Helper, dir string) (err error) {
  14. testfixtures.SkipDatabaseNameCheck(true)
  15. fixtures, err = testfixtures.NewFolder(x.DB().DB, helper, dir)
  16. return err
  17. }
  18. // LoadFixtures load fixtures for a test database
  19. func LoadFixtures() error {
  20. var err error
  21. // Database transaction conflicts could occur and result in ROLLBACK
  22. // As a simple workaround, we just retry 20 times.
  23. for i := 0; i < 20; i++ {
  24. err = fixtures.Load()
  25. if err == nil {
  26. break
  27. }
  28. time.Sleep(200 * time.Millisecond)
  29. }
  30. if err != nil {
  31. fmt.Printf("LoadFixtures failed after retries: %v\n", err)
  32. }
  33. // Now if we're running postgres we need to tell it to update the sequences
  34. if x.Dialect().URI().DBType == schemas.POSTGRES {
  35. results, err := x.QueryString(`SELECT 'SELECT SETVAL(' ||
  36. quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) ||
  37. ', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' ||
  38. quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';'
  39. FROM pg_class AS S,
  40. pg_depend AS D,
  41. pg_class AS T,
  42. pg_attribute AS C,
  43. pg_tables AS PGT
  44. WHERE S.relkind = 'S'
  45. AND S.oid = D.objid
  46. AND D.refobjid = T.oid
  47. AND D.refobjid = C.attrelid
  48. AND D.refobjsubid = C.attnum
  49. AND T.relname = PGT.tablename
  50. ORDER BY S.relname;`)
  51. if err != nil {
  52. fmt.Printf("Failed to generate sequence update: %v\n", err)
  53. return err
  54. }
  55. for _, r := range results {
  56. for _, value := range r {
  57. _, err = x.Exec(value)
  58. if err != nil {
  59. fmt.Printf("Failed to update sequence: %s Error: %v\n", value, err)
  60. return err
  61. }
  62. }
  63. }
  64. }
  65. return err
  66. }