Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 55cf856

Browse files
authored
Merge pull request #5 from brunoenten/alternative
handle string size more consistently in mysql dialect
2 parents 3b31e9a + 6c0e701 commit 55cf856

2 files changed

Lines changed: 14 additions & 14 deletions

File tree

dialect_mysql.go

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -72,21 +72,21 @@ func (d MySQLDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool)
7272
return "datetime"
7373
}
7474

75-
if maxsize < 1 {
76-
maxsize = 255
77-
}
78-
7975
/* == About varchar(N) ==
8076
* N is number of characters.
81-
* A varchar column can store up to 65535 bytes.
82-
* Remember that 1 character is 3 bytes in utf-8 charset.
83-
* Also remember that each row can store up to 65535 bytes,
84-
* and you have some overheads, so it's not possible for a
85-
* varchar column to have 65535/3 characters really.
86-
* So it would be better to use 'text' type in stead of
87-
* large varchar type.
77+
* According to the documentation, 0 < N <= 65535.
78+
* But one utf-8 character takes 3 bytes and each row can
79+
* be only 65535 bytes. So there is no way to know exactly
80+
* how many chars a varchar column can actually store.
81+
* Text columns contribute only up to 12 bytes to the row
82+
* size as their contents are stored off-page.
83+
* Hence, we use a conservative maximum of 512 for varchar,
84+
* after which we switch to the text type.
8885
*/
89-
if maxsize < 256 {
86+
if maxsize == 0 {
87+
// Closer match for unbounded text
88+
return "longtext"
89+
} else if maxsize < 256 {
9090
return fmt.Sprintf("varchar(%d)", maxsize)
9191
} else {
9292
return "text"

dialect_mysql_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,9 @@ var _ = Describe("MySQLDialect", func() {
6161
Entry("NullFloat64", sql.NullFloat64{}, 0, false, "double"),
6262
Entry("NullBool", sql.NullBool{}, 0, false, "tinyint"),
6363
Entry("Time", time.Time{}, 0, false, "datetime"),
64-
Entry("default-size string", "", 0, false, "varchar(255)"),
64+
Entry("default-size string", "", 0, false, "longtext"),
6565
Entry("sized string", "", 50, false, "varchar(50)"),
66-
Entry("large string", "", 1024, false, "text"),
66+
Entry("large string", "", 1024, false, "text(1024)"),
6767
)
6868

6969
Describe("AutoIncrStr", func() {

0 commit comments

Comments
 (0)