I want to do a case-insensitive search in Golang. I am using this library.
I have tried the following but its not working.
someId = "abc"
model := abcModel{Id: someId}
result := p.db.Where("lower(id) = lower(?)", someId).Take(&model)
Id is primary-key here
I have also tried
db.Where("LOWER(id) LIKE LOWER(?)", fmt.Sprintf("%%%s%%", someId)).Take(&model)
Could someone please help here. Not sure whats going wrong. Any pointers would be appreciated.
Thanks!
EDIT:
This is what I have in DB
id | created_at | updated_at | deleted_at | client_id | ttl | client_type | token | expires_on
--------------------------------------+-------------------------------+-------------------------------+------------+--------------------------------------+------+--------------------------------------+
ABC | 2023-10-30 16:10:59.614132+00 | 2023-10-30 16:10:59.614132+00 | | ae30e377 | 100 | 7da0e618-7393-45c2-94dc-5e7b1d6c1610 | abc | 2023-10-30 16:27:39.613566+00
and I was hoping that above query would return this record in DB since its a case-insensitive search.
The error that I am getting is record not found
https://gorm.io/docs/error_handling.html#ErrRecordNotFound
I am running Postgres server in a docker container. https://hub.docker.com/_/postgres
It is unclear what p
represents, but here is a working example using both Take()
and Where().Take()
:
func main() {
// open connection to postgres
db, err := gorm.Open(postgres.New(...), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// Get the row
someId := "abc"
var result abcModel
db.Take(&result, "lower(id) = lower(?)", someId)
// Print the row
fmt.Println(result)
// Find the row using Where
var result2 abcModel
db.Where("lower(id) = lower(?)", someId).Take(&result2)
// Print the row
fmt.Println(result2)
}
Output:
$ go run .
{ABC 2023-10-30 10:00:57.774905 -0700 PDT 2023-10-30 10:00:57.774905 -0700 PDT <nil> ae30e377 100 7da0e618-7393-45c2-94dc-5e7b1d6c1610 abc 2023-10-30 10:00:57.774906 -0700 PDT}
{ABC 2023-10-30 10:00:57.774905 -0700 PDT 2023-10-30 10:00:57.774905 -0700 PDT <nil> ae30e377 100 7da0e618-7393-45c2-94dc-5e7b1d6c1610 abc 2023-10-30 10:00:57.774906 -0700 PDT}
Therefore, your original code seems to work, except that perhaps your error has something to do with how p
is defined