首頁  >  文章  >  後端開發  >  Gorm 在自訂字串類型上傳回掃描器錯誤

Gorm 在自訂字串類型上傳回掃描器錯誤

王林
王林轉載
2024-02-11 18:21:211094瀏覽

Gorm 在自定义字符串类型上返回扫描仪错误

php小編香蕉介紹:在Gorm中,當你嘗試在自訂的字串類型上進行掃描操作時,可能會遇到錯誤。這個問題可能會導致掃描器無法正確解析字串,從而導致程式出錯。這是因為Gorm預設使用`Scan`方法來掃描字串類型的字段,但對於自訂的字串類型,`Scan`方法可能無法正確處理。解決這個問題的方法是使用`Value`方法來手動解析字串,確保程式能夠正確執行。透過這種方式,你可以避免在使用Gorm時遇到關於掃描器錯誤的問題。

問題內容

我寫了以下實體:

type datacategory string

const (
    datacategory1 datacategory = "category1"
    datacategory2 datacategory = "category2"
)

type data struct {
    name            string         `json:"name"`
    categories      []datacategory `json:"category" gorm:"type:text[]"`
}

我在資料庫中手動建立了一行,並用 category1 和 category2 填充了類別數組類型。

但是讀取資料時會出現以下錯誤:

sql: scan error on column index 19, name "category": unsupported scan, storing driver.value type string into type *[]datacategory

範例值方法:

func (s DataCategorySlice) Value() (driver.Value, error) {
    if s == nil {
        return nil, nil
    }
    if len(s) == 0 {
        return "{}", nil
    }

    v := []string{}
    for _, dc := range s {
        v = append(v, string(dc))
    }
    result := fmt.Sprintf("{%s}", strings.Join(v, ","))
    return result, nil
}

解決方法

以下範例假設您使用 postgresql 作為 rdbms,並且 datacategory 值不包含逗號或未轉義的單引號。

// declare the custom type
type datacategoryslice []datacategory
// implement driver.valuer to encode the value into the
// correct format that is accepted by the target rdbms
func (s datacategoryslice) value() (driver.value, error) {
    if s == nil {
        return nil, nil
    }
    if len(s) == 0 {
        return []byte(`{}`), nil
    }

    v := []byte(`{`)
    for i := range s {
        v = append(v, s[i]...)
        v = append(v, ',')
    }
    v[len(v)-1] = '}' // replace last comma with closing brace
    return v, nil
}
// implement scanner to decode the raw source
// value as retrieved from the database
func (s *datacategoryslice) scan(src any) error {
    var data []byte
    switch v := src.(type) {
    case []byte:
        data = v
    case string:
        data = []byte(v)
    case nil:
        return nil
    default:
        return fmt.errorf("unsupported type: %t", src)
    }
    if len(data) == 0 {
        return nil
    }
    data = data[1:len(data)-1] // remove surrounding braces
    for _, v := range bytes.split(data, []byte{','}) {
        *s = append(*s, datacategory(v))
    }
    return nil
}

或者,如果從value() (driver.value, error) 傳回<code>[]byte 不起作用,例如它會導致「錯誤:格式錯誤的陣列文字: 38ee7a7778c5dd4d693371ecf1d81766 (sqlstate 22p02)”,那麼您可以嘗試使用string 作為傳回類型。

來自@kozhioyrin的範例

// implement driver.Valuer to encode the value into the
// correct format that is accepted by the target RDBMS
func (s DataCategorySlice) Value() (driver.Value, error) {
    if s == nil {
        return nil, nil
    }
    if len(s) == 0 {
        return "{}", nil
    }

    v := []string{}
    for _, dc := range s {
        v = append(v, string(dc))
    }
    result := fmt.Sprintf("{%s}", strings.Join(v, ","))
    return result, nil
}

以上是Gorm 在自訂字串類型上傳回掃描器錯誤的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除