Beispiel #1
0
func (e *Evaluator) funcConvert(f *ast.FuncConvertExpr) bool {
	value := f.Expr.GetValue()

	// Casting nil to any type returns nil
	if value == nil {
		f.SetValue(nil)
		return true
	}
	str, ok := value.(string)
	if !ok {
		return true
	}
	if strings.ToLower(f.Charset) == "ascii" {
		f.SetValue(value)
		return true
	} else if strings.ToLower(f.Charset) == "utf8mb4" {
		f.SetValue(value)
		return true
	}

	encoding, _ := charset.Lookup(f.Charset)
	if encoding == nil {
		e.err = ErrInvalidOperation.Gen("unknown encoding: %s", f.Charset)
		return false
	}

	target, _, err := transform.String(encoding.NewDecoder(), str)
	if err != nil {
		log.Errorf("Convert %s to %s with error: %v", str, f.Charset, err)
		e.err = errors.Trace(err)
		return false
	}
	f.SetValue(target)
	return true
}
Beispiel #2
0
// See https://dev.mysql.com/doc/refman/5.7/en/cast-functions.html#function_convert
func builtinConvert(args []types.Datum, _ context.Context) (d types.Datum, err error) {
	// Casting nil to any type returns nil
	if args[0].Kind() != types.KindString {
		return d, nil
	}

	str := args[0].GetString()
	Charset := args[1].GetString()

	if strings.ToLower(Charset) == "ascii" {
		d.SetString(str)
		return d, nil
	} else if strings.ToLower(Charset) == "utf8mb4" {
		d.SetString(str)
		return d, nil
	}

	encoding, _ := charset.Lookup(Charset)
	if encoding == nil {
		return d, errors.Errorf("unknown encoding: %s", Charset)
	}

	target, _, err := transform.String(encoding.NewDecoder(), str)
	if err != nil {
		log.Errorf("Convert %s to %s with error: %v", str, Charset, err)
		return d, errors.Trace(err)
	}
	d.SetString(target)
	return d, nil
}