How to apply a multiple check constraint in gorm with sqlite?

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?

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” :rofl: :rofl:


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)

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.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.