How to Handle Nullable String Fields with GORM and sql.NullString?

Mary-Kate Olsen
Release: 2024-11-06 03:29:02
Original
637 people have browsed it

How to Handle Nullable String Fields with GORM and sql.NullString?

Unable to Use Type String as sql.NullString

Query

In GORM, using sql.NullString for a field that may be NULL faces the error:

cannot use "a string goes here", (type string) as type sql.NullString in field value
Copy after login

while trying to execute a simple GORM validation example.

Resolution

sql.NullString is not a string type but a struct type defined as:

type NullString struct {
    String string
    Valid  bool // Valid is true if String is not NULL
}
Copy after login

To initialize it correctly, use the following syntax:

db.Create(&Day{
    Nameday:     "Monday",
    Dateday:     "23-10-2019",
    Something:   sql.NullString{String: "a string goes here", Valid: true},
    Holyday:     false,
})
Copy after login

Alternative Solution

Alternatively, to retain the simpler initialization syntax:

  1. Define a custom nullable string type:

    type MyString string
    Copy after login
  2. Implement the sql.Scanner and driver.Valuer interfaces to handle value conversion.
  3. Override the methods Value() and Scan() as follows:

    func (s MyString) Value() (driver.Value, error) {
        if s == MyStringNull {
            return nil, nil
        }
        return []byte(s), nil
    }
    
    func (s *MyString) Scan(src interface{}) error {
        switch v := src.(type) {
        case string:
            *s = MyString(v)
        case []byte:
            *s = MyString(v)
        case nil:
            *s = MyStringNull
        }
        return nil
    }
    Copy after login
  4. Declare the Something field as MyString and initialize it as intended:

    db.Create(&Day{
        Nameday:     "Monday",
        Dateday:     "23-10-2019",
        // Here, an untyped string constant will explicitly convert to MyString because they have the same underlying type.
        Something:   "a string goes here",
        Holyday:     false,
    })
    Copy after login

The above is the detailed content of How to Handle Nullable String Fields with GORM and sql.NullString?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!