dialect/sql/schema: add field collation support (#1548)

* specific field collation support

* go generate ./...
This commit is contained in:
Mahmudul Haque
2021-05-09 21:09:08 +06:00
committed by GitHub
parent a2a6af4cd8
commit ba954ebeec
6 changed files with 52 additions and 2 deletions

View File

@@ -284,6 +284,8 @@ func (d *MySQL) addColumn(c *Column) *sql.ColumnBuilder {
if c.Increment {
b.Attr("AUTO_INCREMENT")
}
c.collation(b)
c.nullable(b)
c.defaultValue(b)
if c.Type == field.TypeJSON {

View File

@@ -78,6 +78,40 @@ func TestMySQL_Create(t *testing.T) {
mock.ExpectCommit()
},
},
{
name: "create new table with specific field collation",
tables: []*Table{
{
Name: "users",
PrimaryKey: []*Column{
{Name: "id", Type: field.TypeInt, Increment: true},
},
Columns: []*Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString, Nullable: true},
{Name: "address", Type: field.TypeString, Nullable: true, Collation: "utf8_unicode_ci"},
{Name: "age", Type: field.TypeInt},
{Name: "doc", Type: field.TypeJSON, Nullable: true},
{Name: "enums", Type: field.TypeEnum, Enums: []string{"a", "b"}},
{Name: "uuid", Type: field.TypeUUID, Nullable: true},
{Name: "datetime", Type: field.TypeTime, SchemaType: map[string]string{dialect.MySQL: "datetime"}, Default: "CURRENT_TIMESTAMP"},
{Name: "decimal", Type: field.TypeFloat32, SchemaType: map[string]string{dialect.MySQL: "decimal(6,2)"}},
},
Annotation: &entsql.Annotation{
Charset: "utf8",
Collation: "utf8_general_ci",
Options: "ENGINE = INNODB",
},
},
},
before: func(mock mysqlMock) {
mock.start("5.7.33")
mock.tableExists("users", false)
mock.ExpectExec(escape("CREATE TABLE IF NOT EXISTS `users`(`id` bigint AUTO_INCREMENT NOT NULL, `name` varchar(255) NULL, `address` varchar(255) COLLATE utf8_unicode_ci NULL, `age` bigint NOT NULL, `doc` json NULL, `enums` enum('a', 'b') NOT NULL, `uuid` char(36) binary NULL, `datetime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `decimal` decimal(6,2) NOT NULL, PRIMARY KEY(`id`)) CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = INNODB")).
WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectCommit()
},
},
{
name: "create new table 5.6",
tables: []*Table{

View File

@@ -176,6 +176,7 @@ type Column struct {
Nullable bool // null or not null attribute.
Default interface{} // default value.
Enums []string // enum values.
Collation string // collation type (utf8mb4_unicode_ci, utf8mb4_general_ci)
typ string // row column type (used for Rows.Scan).
indexes Indexes // linked indexes.
foreign *ForeignKey // linked foreign-key.
@@ -307,6 +308,13 @@ func (c Column) supportDefault() bool {
}
}
// collation adds `COLLATE collation_name`.
func (c *Column) collation(b *sql.ColumnBuilder) {
if c.Collation != "" {
b.Attr("COLLATE " + c.Collation)
}
}
// unique adds the `UNIQUE` attribute if the column is a unique type.
// it is exist in a different function to share the common declaration
// between the two dialects.