Skip to content

Commit

Permalink
use case-sensitive collation for mysql/mssql
Browse files Browse the repository at this point in the history
  • Loading branch information
wxiaoguang committed Dec 31, 2023
1 parent cb10f27 commit ebc65a7
Show file tree
Hide file tree
Showing 19 changed files with 401 additions and 51 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ _test
.idea
# Goland's output filename can not be set manually
/go_build_*
/gitea_*

# MS VSCode
.vscode
Expand Down
4 changes: 2 additions & 2 deletions cmd/doctor_convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ func runDoctorConvert(ctx *cli.Context) error {

switch {
case setting.Database.Type.IsMySQL():
if err := db.ConvertUtf8ToUtf8mb4(); err != nil {
log.Fatal("Failed to convert database from utf8 to utf8mb4: %v", err)
if err := db.ConvertDatabaseTable(); err != nil {
log.Fatal("Failed to convert database & table: %v", err)
return err
}
fmt.Println("Converted successfully, please confirm your database's character set is now utf8mb4")
Expand Down
2 changes: 2 additions & 0 deletions custom/conf/app.example.ini
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,7 @@ NAME = gitea
USER = root
;PASSWD = ;Use PASSWD = `your password` for quoting if you use special characters in the password.
;SSL_MODE = false ; either "false" (default), "true", or "skip-verify"
;CHARSET_COLLATION = ; Empty as default, Gitea will try to find a case-sensitive collation. Don't change it unless you clearly know what you need.
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
Expand Down Expand Up @@ -382,6 +383,7 @@ USER = root
;NAME = gitea
;USER = SA
;PASSWD = MwantsaSecurePassword1
;CHARSET_COLLATION = ; Empty as default, Gitea will try to find a case-sensitive collation. Don't change it unless you clearly know what you need.
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
Expand Down
1 change: 1 addition & 0 deletions docs/content/administration/config-cheat-sheet.en-us.md
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,7 @@ The following configuration set `Content-Type: application/vnd.android.package-a
- `NAME`: **gitea**: Database name.
- `USER`: **root**: Database username.
- `PASSWD`: **_empty_**: Database user password. Use \`your password\` or """your password""" for quoting if you use special characters in the password.
- `CHARSET_COLLATION`: **_empty_**: (MySQL/MSSQL only) Gitea expects to use a case-sensitive collation for database. Leave it empty to use the default collation decided by the Gitea. Don't change it unless you clearly know what you need.
- `SCHEMA`: **_empty_**: For PostgreSQL only, schema to use if different from "public". The schema must exist beforehand,
the user must have creation privileges on it, and the user search path must be set to the look into the schema first
(e.g. `ALTER USER user SET SEARCH_PATH = schema_name,"$user",public;`).
Expand Down
18 changes: 0 additions & 18 deletions docs/content/help/faq.en-us.md
Original file line number Diff line number Diff line change
Expand Up @@ -371,24 +371,6 @@ If you are receiving an error line containing `Error 1071: Specified key was too
then you are attempting to run Gitea on tables which use the ISAM engine. While this may have worked by chance in previous versions of Gitea, it has never been officially supported and
you must use InnoDB. You should run `ALTER TABLE table_name ENGINE=InnoDB;` for each table in the database.

If you are using MySQL 5, another possible fix is

```mysql
SET GLOBAL innodb_file_format=Barracuda;
SET GLOBAL innodb_file_per_table=1;
SET GLOBAL innodb_large_prefix=1;
```

## Why Are Emoji Broken On MySQL

Unfortunately MySQL's `utf8` charset does not completely allow all possible UTF-8 characters, in particular Emoji.
They created a new charset and collation called `utf8mb4` that allows for emoji to be stored but tables which use
the `utf8` charset, and connections which use the `utf8` charset will not use this.

Please run `gitea doctor convert`, or run `ALTER DATABASE database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;`
for the database_name and run `ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;`
for each table in the database.

## Why are Emoji displaying only as placeholders or in monochrome

Gitea requires the system or browser to have one of the supported Emoji fonts installed, which are Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji and Twemoji Mozilla. Generally, the operating system should already provide one of these fonts, but especially on Linux, it may be necessary to install them manually.
Expand Down
19 changes: 0 additions & 19 deletions docs/content/help/faq.zh-cn.md
Original file line number Diff line number Diff line change
Expand Up @@ -375,25 +375,6 @@ Gitea 提供了一个子命令`gitea migrate`来初始化数据库,然后您
的错误行,则表示您正在尝试在使用 ISAM 引擎的表上运行 Gitea。尽管在先前版本的 Gitea 中可能是凑巧能够工作的,但它从未得到官方支持,
您必须使用 InnoDB。您应该对数据库中的每个表运行`ALTER TABLE table_name ENGINE=InnoDB;`

如果您使用的是 MySQL 5,另一个可能的修复方法是:

```mysql
SET GLOBAL innodb_file_format=Barracuda;
SET GLOBAL innodb_file_per_table=1;
SET GLOBAL innodb_large_prefix=1;
```

## 为什么 MySQL 上的 Emoji 显示错误

不幸的是,MySQL 的`utf8`字符集不完全允许所有可能的 UTF-8 字符,特别是 Emoji。
他们创建了一个名为 `utf8mb4`的字符集和校对规则,允许存储 Emoji,但使用
utf8 字符集的表和连接将不会使用它。

请运行 `gitea doctor convert` 或对数据库运行 `ALTER DATABASE database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;`
并对每个表运行 `ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;`

您还需要将`app.ini`文件中的数据库字符集设置为`CHARSET=utf8mb4`

## 为什么 Emoji 只显示占位符或单色图像

Gitea 需要系统或浏览器安装其中一个受支持的 Emoji 字体,例如 Apple Color Emoji、Segoe UI Emoji、Segoe UI Symbol、Noto Color Emoji 和 Twemoji Mozilla。通常,操作系统应该已经提供了其中一个字体,但特别是在 Linux 上,可能需要手动安装它们。
Expand Down
8 changes: 6 additions & 2 deletions docs/content/installation/database-preparation.en-us.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,14 @@ Note: All steps below requires that the database engine of your choice is instal

Replace username and password above as appropriate.

4. Create database with UTF-8 charset and collation. Make sure to use `utf8mb4` charset instead of `utf8` as the former supports all Unicode characters (including emojis) beyond _Basic Multilingual Plane_. Also, collation chosen depending on your expected content. When in doubt, use either `unicode_ci` or `general_ci`.
4. Create database with UTF-8 charset and case-sensitive collation.

`utf8mb4_bin` is a common collation for both MySQL/MariaDB.
When Gitea starts, it will try to find a better collation (`utf8mb4_0900_as_cs` or `uca1400_as_cs`) and alter the database if it is possible.
If you would like to use other collation, you can set `[database].CHARSET_COLLATION` in the `app.ini` file.

```sql
CREATE DATABASE giteadb CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_unicode_ci';
CREATE DATABASE giteadb CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_bin';
```

Replace database name as appropriate.
Expand Down
6 changes: 4 additions & 2 deletions docs/content/installation/database-preparation.zh-cn.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,12 @@ menu:

根据需要替换上述用户名和密码。

4. 使用 UTF-8 字符集和排序规则创建数据库。确保使用 `**utf8mb4**` 字符集,而不是 `utf8`,因为前者支持 _Basic Multilingual Plane_ 之外的所有 Unicode 字符(包括表情符号)。排序规则根据您预期的内容选择。如果不确定,可以使用 `unicode_ci` 或 `general_ci`。
4. 使用 UTF-8 字符集和大小写敏感的排序规则创建数据库。

Gitea 启动后会尝试把数据库修改为更合适的字符集,如果你想指定自己的字符集规则,可以在 app.ini 中设置 `[database].CHARSET_COLLATION`。

```sql
CREATE DATABASE giteadb CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_unicode_ci';
CREATE DATABASE giteadb CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_bin';
```

根据需要替换数据库名称。
Expand Down
182 changes: 182 additions & 0 deletions models/db/collation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package db

import (
"errors"
"fmt"
"strings"

"code.gitea.io/gitea/modules/container"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"

"xorm.io/xorm"
"xorm.io/xorm/schemas"
)

type CheckCollationsResult struct {
ExpectedCollation string
AvailableCollation container.Set[string]
DatabaseCollation string
IsCollationCaseSensitive func(s string) bool
CollationEquals func(a, b string) bool

InconsistentCollationColumns []string
}

func findAvailableCollationsMySQL(x *xorm.Engine) (ret container.Set[string], err error) {
var res []struct {
Collation string
}
if err = x.SQL("SHOW COLLATION WHERE (Collation = 'utf8mb4_bin') OR (Collation LIKE '%\\_as\\_cs%')").Find(&res); err != nil {
return nil, err
}
ret = make(container.Set[string], len(res))
for _, r := range res {
ret.Add(r.Collation)
}
return ret, nil
}

func findAvailableCollationsMSSQL(x *xorm.Engine) (ret container.Set[string], err error) {
var res []struct {
Name string
}
if err = x.SQL("SELECT * FROM sys.fn_helpcollations() WHERE name LIKE '%\\_CS\\_AS%'").Find(&res); err != nil {
return nil, err
}
ret = make(container.Set[string], len(res))
for _, r := range res {
ret.Add(r.Name)
}
return ret, nil
}

func CheckCollations(x *xorm.Engine) (*CheckCollationsResult, error) {
dbTables, err := x.DBMetas()
if err != nil {
return nil, err
}

res := &CheckCollationsResult{}
res.CollationEquals = func(a, b string) bool { return a == b }

var candidateCollations []string
if x.Dialect().URI().DBType == schemas.MYSQL {
if _, err = x.SQL("SELECT @@collation_database").Get(&res.DatabaseCollation); err != nil {
return nil, err
}
res.IsCollationCaseSensitive = func(s string) bool {
return s == "utf8mb4_bin" || strings.HasSuffix(s, "_as_cs")
}
candidateCollations = []string{"utf8mb4_0900_as_cs", "uca1400_as_cs", "utf8mb4_bin"}
res.AvailableCollation, err = findAvailableCollationsMySQL(x)
if err != nil {
return nil, err
}
res.CollationEquals = func(a, b string) bool {
// MariaDB adds the "utf8mb4_" prefix, eg: "utf8mb4_uca1400_as_cs", but not the name "uca1400_as_cs" in "SHOW COLLATION"
// At the moment, it's safe to ignore the database difference, just trim the prefix and compare. It could be fixed easily if there is any problem in the future.
return a == b || strings.TrimPrefix(a, "utf8mb4_") == strings.TrimPrefix(b, "utf8mb4_")
}
} else if x.Dialect().URI().DBType == schemas.MSSQL {
if _, err = x.SQL("SELECT DATABASEPROPERTYEX(DB_NAME(), 'Collation')").Get(&res.DatabaseCollation); err != nil {
return nil, err
}
res.IsCollationCaseSensitive = func(s string) bool {
return strings.HasSuffix(s, "_CS_AS")
}
candidateCollations = []string{"Latin1_General_CS_AS"}
res.AvailableCollation, err = findAvailableCollationsMSSQL(x)
if err != nil {
return nil, err
}
} else {
return nil, nil
}

if res.DatabaseCollation == "" {
return nil, errors.New("unable to get collation for current database")
}

res.ExpectedCollation = setting.Database.CharsetCollation
if res.ExpectedCollation == "" {
for _, collation := range candidateCollations {
if res.AvailableCollation.Contains(collation) {
res.ExpectedCollation = collation
break
}
}
}

if res.ExpectedCollation == "" {
return nil, errors.New("unable to find a suitable collation for current database")
}

allColumnsMatchExpected := true
for _, table := range dbTables {
for _, col := range table.Columns() {
if col.Collation != "" {
allColumnsMatchExpected = allColumnsMatchExpected && res.CollationEquals(col.Collation, res.ExpectedCollation)
if !res.IsCollationCaseSensitive(col.Collation) || !res.CollationEquals(col.Collation, res.DatabaseCollation) {
res.InconsistentCollationColumns = append(res.InconsistentCollationColumns, fmt.Sprintf("%s.%s", table.Name, col.Name))
}
}
}
}
// if all columns match expected collation, then it could also be considered as "consistent"
if allColumnsMatchExpected {
res.InconsistentCollationColumns = nil
}
return res, nil
}

func CheckCollationsDefaultEngine() (*CheckCollationsResult, error) {
return CheckCollations(x)
}

func alterDatabaseCollation(x *xorm.Engine, collation string) error {
if x.Dialect().URI().DBType == schemas.MYSQL {
_, err := x.Exec("ALTER DATABASE CHARACTER SET utf8mb4 COLLATE " + collation)
return err
} else if x.Dialect().URI().DBType == schemas.MSSQL {
// MSSQL has many limitations on changing database collation, it could fail in many cases
_, err := x.Exec("ALTER DATABASE CURRENT COLLATE " + collation)
return err
}
return errors.New("unsupported database type")
}

func preprocessDatabaseCollation(x *xorm.Engine) {
// check database & table collation, and alter the database collation if needed
r, err := CheckCollations(x)
if err != nil {
log.Error("Failed to check database collation: %v")
}
if r == nil {
return // no check result means the database doesn't need to do such check/process (at the moment ....)
}

// try to alter database collation to expected, it might fail in some cases (and it isn't necessary to succeed)
if !r.CollationEquals(r.DatabaseCollation, r.ExpectedCollation) {
if err = alterDatabaseCollation(x, r.ExpectedCollation); err != nil {
log.Error("Failed to change database collation to %q: %v", r.ExpectedCollation, err)
} else {
if r, err = CheckCollations(x); err != nil {
log.Fatal("Failed to check database collation again after altering: %v", err) // impossible case
}
log.Warn("Current database has been altered to use collation %q", r.DatabaseCollation)
}
}

// check column collation, and show warning/error to end users -- no need to fatal and do not block the startup
if !r.IsCollationCaseSensitive(r.DatabaseCollation) {
log.Warn("Current database is using a case-insensitive collation %q, although Gitea could work with it, there might be some rare cases which don't work as expected.", r.DatabaseCollation)
}

if len(r.InconsistentCollationColumns) > 0 {
log.Error("There are %d table columns have inconsistent collation, they should use %q. Please go to admin panel Self Check page or refer to Gitea document", len(r.InconsistentCollationColumns), r.DatabaseCollation)
}
}
15 changes: 10 additions & 5 deletions models/db/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,18 @@ import (
"xorm.io/xorm/schemas"
)

// ConvertUtf8ToUtf8mb4 converts database and tables from utf8 to utf8mb4 if it's mysql and set ROW_FORMAT=dynamic
func ConvertUtf8ToUtf8mb4() error {
// ConvertDatabaseTable converts database and tables from utf8 to utf8mb4 if it's mysql and set ROW_FORMAT=dynamic
func ConvertDatabaseTable() error {
if x.Dialect().URI().DBType != schemas.MYSQL {
return nil
}

_, err := x.Exec(fmt.Sprintf("ALTER DATABASE `%s` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci", setting.Database.Name))
r, err := CheckCollations(x)
if err != nil {
return err
}

_, err = x.Exec(fmt.Sprintf("ALTER DATABASE `%s` CHARACTER SET utf8mb4 COLLATE %s", setting.Database.Name, r.ExpectedCollation))
if err != nil {
return err
}
Expand All @@ -30,11 +35,11 @@ func ConvertUtf8ToUtf8mb4() error {
return err
}
for _, table := range tables {
if _, err := x.Exec(fmt.Sprintf("ALTER TABLE `%s` ROW_FORMAT=dynamic;", table.Name)); err != nil {
if _, err := x.Exec(fmt.Sprintf("ALTER TABLE `%s` ROW_FORMAT=dynamic", table.Name)); err != nil {
return err
}

if _, err := x.Exec(fmt.Sprintf("ALTER TABLE `%s` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;", table.Name)); err != nil {
if _, err := x.Exec(fmt.Sprintf("ALTER TABLE `%s` CONVERT TO CHARACTER SET utf8mb4 COLLATE %s", table.Name, r.ExpectedCollation)); err != nil {
return err
}
}
Expand Down
2 changes: 2 additions & 0 deletions models/db/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,8 @@ func InitEngineWithMigration(ctx context.Context, migrateFunc func(*xorm.Engine)
return err
}

preprocessDatabaseCollation(x)

if err = x.Ping(); err != nil {
return err
}
Expand Down
7 changes: 4 additions & 3 deletions modules/setting/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ var (
Path string
LogSQL bool
MysqlCharset string
CharsetCollation string
Timeout int // seconds
SQLiteJournalMode string
DBConnectRetries int
Expand Down Expand Up @@ -67,7 +68,7 @@ func loadDBSetting(rootCfg ConfigProvider) {
}
Database.Schema = sec.Key("SCHEMA").String()
Database.SSLMode = sec.Key("SSL_MODE").MustString("disable")
Database.MysqlCharset = sec.Key("MYSQL_CHARSET").MustString("utf8mb4") // do not document it, end users won't need it.
Database.CharsetCollation = sec.Key("CHARSET_COLLATION").String()

Database.Path = sec.Key("PATH").MustString(filepath.Join(AppDataPath, "gitea.db"))
Database.Timeout = sec.Key("SQLITE_TIMEOUT").MustInt(500)
Expand Down Expand Up @@ -105,8 +106,8 @@ func DBConnStr() (string, error) {
if tls == "disable" { // allow (Postgres-inspired) default value to work in MySQL
tls = "false"
}
connStr = fmt.Sprintf("%s:%s@%s(%s)/%s%scharset=%s&parseTime=true&tls=%s",
Database.User, Database.Passwd, connType, Database.Host, Database.Name, paramSep, Database.MysqlCharset, tls)
connStr = fmt.Sprintf("%s:%s@%s(%s)/%s%sparseTime=true&tls=%s",
Database.User, Database.Passwd, connType, Database.Host, Database.Name, paramSep, tls)
case "postgres":
connStr = getPostgreSQLConnectionString(Database.Host, Database.User, Database.Passwd, Database.Name, Database.SSLMode)
case "mssql":
Expand Down
Loading

0 comments on commit ebc65a7

Please sign in to comment.