Skip to content

Commit 9723eac

Browse files
authored
Add varchar limit detection as per PostgreSQL limits (#302)
* Add varchar limit detection as per https://www.postgresql.org/docs/current/datatype-character.html * Add tests for String type
1 parent dcfe4ea commit 9723eac

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

postgres.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ func (dialector Dialector) DataTypeOf(field *schema.Field) string {
228228
}
229229
return "decimal"
230230
case schema.String:
231-
if field.Size > 0 {
231+
if field.Size > 0 && field.Size <= 10485760 {
232232
return fmt.Sprintf("varchar(%d)", field.Size)
233233
}
234234
return "text"

postgres_test.go

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package postgres
2+
3+
import (
4+
"testing"
5+
"gorm.io/gorm/schema"
6+
)
7+
8+
func Test_DataTypeOf(t *testing.T) {
9+
type fields struct {
10+
Config *Config
11+
}
12+
type args struct {
13+
field *schema.Field
14+
}
15+
tests := []struct {
16+
name string
17+
fields fields
18+
args args
19+
want string
20+
} {
21+
{
22+
name: "it should return boolean",
23+
args: args{field: &schema.Field{DataType: schema.Bool}},
24+
want: "boolean",
25+
},
26+
{
27+
name: "it should return text -1",
28+
args: args{field: &schema.Field{DataType: schema.String, Size: -1}},
29+
want: "text",
30+
},
31+
{
32+
name: "it should return text > 10485760",
33+
args: args{field: &schema.Field{DataType: schema.String, Size: 12345678}},
34+
want: "text",
35+
},
36+
{
37+
name: "it should return varchar(100)",
38+
args: args{field: &schema.Field{DataType: schema.String, Size: 100}},
39+
want: "varchar(100)",
40+
},
41+
{
42+
name: "it should return varchar(10485760)",
43+
args: args{field: &schema.Field{DataType: schema.String, Size: 10485760}},
44+
want: "varchar(10485760)",
45+
},
46+
}
47+
for _, tt := range tests {
48+
t.Run(tt.name, func(t *testing.T) {
49+
dialector := Dialector{
50+
Config: tt.fields.Config,
51+
}
52+
if got := dialector.DataTypeOf(tt.args.field); got != tt.want {
53+
t.Errorf("DataTypeOf() = %v, want %v", got, tt.want)
54+
}
55+
})
56+
}
57+
}

0 commit comments

Comments
 (0)