gitea源码

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package db
  4. import (
  5. "fmt"
  6. "strconv"
  7. "code.gitea.io/gitea/modules/log"
  8. "code.gitea.io/gitea/modules/setting"
  9. "xorm.io/xorm"
  10. "xorm.io/xorm/schemas"
  11. )
  12. // ConvertDatabaseTable converts database and tables from utf8 to utf8mb4 if it's mysql and set ROW_FORMAT=dynamic
  13. func ConvertDatabaseTable() error {
  14. if xormEngine.Dialect().URI().DBType != schemas.MYSQL {
  15. return nil
  16. }
  17. r, err := CheckCollations(xormEngine)
  18. if err != nil {
  19. return err
  20. }
  21. _, err = xormEngine.Exec(fmt.Sprintf("ALTER DATABASE `%s` CHARACTER SET utf8mb4 COLLATE %s", setting.Database.Name, r.ExpectedCollation))
  22. if err != nil {
  23. return err
  24. }
  25. tables, err := xormEngine.DBMetas()
  26. if err != nil {
  27. return err
  28. }
  29. for _, table := range tables {
  30. if _, err := xormEngine.Exec(fmt.Sprintf("ALTER TABLE `%s` ROW_FORMAT=dynamic", table.Name)); err != nil {
  31. return err
  32. }
  33. if _, err := xormEngine.Exec(fmt.Sprintf("ALTER TABLE `%s` CONVERT TO CHARACTER SET utf8mb4 COLLATE %s", table.Name, r.ExpectedCollation)); err != nil {
  34. return err
  35. }
  36. }
  37. return nil
  38. }
  39. // ConvertVarcharToNVarchar converts database and tables from varchar to nvarchar if it's mssql
  40. func ConvertVarcharToNVarchar() error {
  41. if xormEngine.Dialect().URI().DBType != schemas.MSSQL {
  42. return nil
  43. }
  44. sess := xormEngine.NewSession()
  45. defer sess.Close()
  46. res, err := sess.QuerySliceString(`SELECT 'ALTER TABLE ' + OBJECT_NAME(SC.object_id) + ' MODIFY SC.name NVARCHAR(' + CONVERT(VARCHAR(5),SC.max_length) + ')'
  47. FROM SYS.columns SC
  48. JOIN SYS.types ST
  49. ON SC.system_type_id = ST.system_type_id
  50. AND SC.user_type_id = ST.user_type_id
  51. WHERE ST.name ='varchar'`)
  52. if err != nil {
  53. return err
  54. }
  55. for _, row := range res {
  56. if len(row) == 1 {
  57. if _, err = sess.Exec(row[0]); err != nil {
  58. return err
  59. }
  60. }
  61. }
  62. return err
  63. }
  64. // Cell2Int64 converts a xorm.Cell type to int64,
  65. // and handles possible irregular cases.
  66. func Cell2Int64(val xorm.Cell) int64 {
  67. switch (*val).(type) {
  68. case []uint8:
  69. log.Trace("Cell2Int64 ([]uint8): %v", *val)
  70. v, _ := strconv.ParseInt(string((*val).([]uint8)), 10, 64)
  71. return v
  72. }
  73. return (*val).(int64)
  74. }