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.

convert.go 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. // ConvertUtf8ToUtf8mb4 converts database and tables from utf8 to utf8mb4 if it's mysql and set ROW_FORMAT=dynamic
  13. func ConvertUtf8ToUtf8mb4() error {
  14. if x.Dialect().URI().DBType != schemas.MYSQL {
  15. return nil
  16. }
  17. _, err := x.Exec(fmt.Sprintf("ALTER DATABASE `%s` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci", setting.Database.Name))
  18. if err != nil {
  19. return err
  20. }
  21. tables, err := x.DBMetas()
  22. if err != nil {
  23. return err
  24. }
  25. for _, table := range tables {
  26. if _, err := x.Exec(fmt.Sprintf("ALTER TABLE `%s` ROW_FORMAT=dynamic;", table.Name)); err != nil {
  27. return err
  28. }
  29. if _, err := x.Exec(fmt.Sprintf("ALTER TABLE `%s` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;", table.Name)); err != nil {
  30. return err
  31. }
  32. }
  33. return nil
  34. }
  35. // ConvertVarcharToNVarchar converts database and tables from varchar to nvarchar if it's mssql
  36. func ConvertVarcharToNVarchar() error {
  37. if x.Dialect().URI().DBType != schemas.MSSQL {
  38. return nil
  39. }
  40. sess := x.NewSession()
  41. defer sess.Close()
  42. res, err := sess.QuerySliceString(`SELECT 'ALTER TABLE ' + OBJECT_NAME(SC.object_id) + ' MODIFY SC.name NVARCHAR(' + CONVERT(VARCHAR(5),SC.max_length) + ')'
  43. FROM SYS.columns SC
  44. JOIN SYS.types ST
  45. ON SC.system_type_id = ST.system_type_id
  46. AND SC.user_type_id = ST.user_type_id
  47. WHERE ST.name ='varchar'`)
  48. if err != nil {
  49. return err
  50. }
  51. for _, row := range res {
  52. if len(row) == 1 {
  53. if _, err = sess.Exec(row[0]); err != nil {
  54. return err
  55. }
  56. }
  57. }
  58. return err
  59. }
  60. // Cell2Int64 converts a xorm.Cell type to int64,
  61. // and handles possible irregular cases.
  62. func Cell2Int64(val xorm.Cell) int64 {
  63. switch (*val).(type) {
  64. case []uint8:
  65. log.Trace("Cell2Int64 ([]uint8): %v", *val)
  66. v, _ := strconv.ParseInt(string((*val).([]uint8)), 10, 64)
  67. return v
  68. }
  69. return (*val).(int64)
  70. }