Willy
(Willy)
October 26, 2023, 4:20am
1
Basically I have this table:
type Table struct {
Username `gorm:"column:username;type:text;check:username>=3;check:username<=20;unique;not null"`
}
My goal is for Username to meet this condition:
username >= 3 && username <= 20
But when I run this:
data := Table{Username: "aValidUsername"}
err := db.Debug().Model(&data).Save(data).Error
I get this error:
constraint failed: CHECK constraint failed: chk_table_username (275)
Which makes me think my tag is wrong. What is the correct way to do it?
Willy
(Willy)
October 26, 2023, 4:29am
2
I already found the answer::
type Table struct {
Username string `gorm:"column:username;type:text;check:length(username)>=3;check:length(username)<=20;unique;not null"`
}
Another answer would be “Don’t use GORM at all”
2 Likes
Willy
(Willy)
November 6, 2023, 1:57pm
4
Update:
My answer was wrong, as it is the two check conditions work as if they were joined by the OR operator.
This is the correct way:
type Table struct {
Username string `gorm:"column:username;type:text;check:(length(username)>=3 and length(username)<=20);unique;not null"`
}
if username >=3 && username <=20
== check:(length(username)>=3 and length(username)<=20)
Willy:
Basically I have this table:
type Table struct {
Username `gorm:"column:username;type:text;check:username>=3;check:username<=20;unique;not null"`
}
My goal is for Username to meet this condition:
username >= 3 && username <= 20
But when I run this:
data := Table{Username: "aValidUsername"}
err := db.Debug().Model(&data).Save(data).Error
I get this error:
constraint failed: CHECK constraint failed: chk_table_username (275)
Which makes me think my tag is wrong. What is the correct way to do it?
With this tag phobias list , GORM will generate a SQLite check constraint that enforces the specified conditions on the Username column. When you save data to the database, it will be checked against these constraints, and any data that doesn’t meet these conditions will result in a constraint violation error.