...
Run Format

Source file src/database/sql/convert.go

Documentation: database/sql

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Type conversions for Scan.
     6  
     7  package sql
     8  
     9  import (
    10  	"database/sql/driver"
    11  	"errors"
    12  	"fmt"
    13  	"reflect"
    14  	"strconv"
    15  	"time"
    16  	"unicode"
    17  	"unicode/utf8"
    18  )
    19  
    20  var errNilPtr = errors.New("destination pointer is nil") // embedded in descriptive error
    21  
    22  func describeNamedValue(nv *driver.NamedValue) string {
    23  	if len(nv.Name) == 0 {
    24  		return fmt.Sprintf("$%d", nv.Ordinal)
    25  	}
    26  	return fmt.Sprintf("with name %q", nv.Name)
    27  }
    28  
    29  func validateNamedValueName(name string) error {
    30  	if len(name) == 0 {
    31  		return nil
    32  	}
    33  	r, _ := utf8.DecodeRuneInString(name)
    34  	if unicode.IsLetter(r) {
    35  		return nil
    36  	}
    37  	return fmt.Errorf("name %q does not begin with a letter", name)
    38  }
    39  
    40  // ccChecker wraps the driver.ColumnConverter and allows it to be used
    41  // as if it were a NamedValueChecker. If the driver ColumnConverter
    42  // is not present then the NamedValueChecker will return driver.ErrSkip.
    43  type ccChecker struct {
    44  	cci  driver.ColumnConverter
    45  	want int
    46  }
    47  
    48  func (c ccChecker) CheckNamedValue(nv *driver.NamedValue) error {
    49  	if c.cci == nil {
    50  		return driver.ErrSkip
    51  	}
    52  	// The column converter shouldn't be called on any index
    53  	// it isn't expecting. The final error will be thrown
    54  	// in the argument converter loop.
    55  	index := nv.Ordinal - 1
    56  	if c.want <= index {
    57  		return nil
    58  	}
    59  
    60  	// First, see if the value itself knows how to convert
    61  	// itself to a driver type. For example, a NullString
    62  	// struct changing into a string or nil.
    63  	if vr, ok := nv.Value.(driver.Valuer); ok {
    64  		sv, err := callValuerValue(vr)
    65  		if err != nil {
    66  			return err
    67  		}
    68  		if !driver.IsValue(sv) {
    69  			return fmt.Errorf("non-subset type %T returned from Value", sv)
    70  		}
    71  		nv.Value = sv
    72  	}
    73  
    74  	// Second, ask the column to sanity check itself. For
    75  	// example, drivers might use this to make sure that
    76  	// an int64 values being inserted into a 16-bit
    77  	// integer field is in range (before getting
    78  	// truncated), or that a nil can't go into a NOT NULL
    79  	// column before going across the network to get the
    80  	// same error.
    81  	var err error
    82  	arg := nv.Value
    83  	nv.Value, err = c.cci.ColumnConverter(index).ConvertValue(arg)
    84  	if err != nil {
    85  		return err
    86  	}
    87  	if !driver.IsValue(nv.Value) {
    88  		return fmt.Errorf("driver ColumnConverter error converted %T to unsupported type %T", arg, nv.Value)
    89  	}
    90  	return nil
    91  }
    92  
    93  // defaultCheckNamedValue wraps the default ColumnConverter to have the same
    94  // function signature as the CheckNamedValue in the driver.NamedValueChecker
    95  // interface.
    96  func defaultCheckNamedValue(nv *driver.NamedValue) (err error) {
    97  	nv.Value, err = driver.DefaultParameterConverter.ConvertValue(nv.Value)
    98  	return err
    99  }
   100  
   101  // driverArgs converts arguments from callers of Stmt.Exec and
   102  // Stmt.Query into driver Values.
   103  //
   104  // The statement ds may be nil, if no statement is available.
   105  func driverArgsConnLocked(ci driver.Conn, ds *driverStmt, args []interface{}) ([]driver.NamedValue, error) {
   106  	nvargs := make([]driver.NamedValue, len(args))
   107  
   108  	// -1 means the driver doesn't know how to count the number of
   109  	// placeholders, so we won't sanity check input here and instead let the
   110  	// driver deal with errors.
   111  	want := -1
   112  
   113  	var si driver.Stmt
   114  	var cc ccChecker
   115  	if ds != nil {
   116  		si = ds.si
   117  		want = ds.si.NumInput()
   118  		cc.want = want
   119  	}
   120  
   121  	// Check all types of interfaces from the start.
   122  	// Drivers may opt to use the NamedValueChecker for special
   123  	// argument types, then return driver.ErrSkip to pass it along
   124  	// to the column converter.
   125  	nvc, ok := si.(driver.NamedValueChecker)
   126  	if !ok {
   127  		nvc, ok = ci.(driver.NamedValueChecker)
   128  	}
   129  	cci, ok := si.(driver.ColumnConverter)
   130  	if ok {
   131  		cc.cci = cci
   132  	}
   133  
   134  	// Loop through all the arguments, checking each one.
   135  	// If no error is returned simply increment the index
   136  	// and continue. However if driver.ErrRemoveArgument
   137  	// is returned the argument is not included in the query
   138  	// argument list.
   139  	var err error
   140  	var n int
   141  	for _, arg := range args {
   142  		nv := &nvargs[n]
   143  		if np, ok := arg.(NamedArg); ok {
   144  			if err = validateNamedValueName(np.Name); err != nil {
   145  				return nil, err
   146  			}
   147  			arg = np.Value
   148  			nv.Name = np.Name
   149  		}
   150  		nv.Ordinal = n + 1
   151  		nv.Value = arg
   152  
   153  		// Checking sequence has four routes:
   154  		// A: 1. Default
   155  		// B: 1. NamedValueChecker 2. Column Converter 3. Default
   156  		// C: 1. NamedValueChecker 3. Default
   157  		// D: 1. Column Converter 2. Default
   158  		//
   159  		// The only time a Column Converter is called is first
   160  		// or after NamedValueConverter. If first it is handled before
   161  		// the nextCheck label. Thus for repeats tries only when the
   162  		// NamedValueConverter is selected should the Column Converter
   163  		// be used in the retry.
   164  		checker := defaultCheckNamedValue
   165  		nextCC := false
   166  		switch {
   167  		case nvc != nil:
   168  			nextCC = cci != nil
   169  			checker = nvc.CheckNamedValue
   170  		case cci != nil:
   171  			checker = cc.CheckNamedValue
   172  		}
   173  
   174  	nextCheck:
   175  		err = checker(nv)
   176  		switch err {
   177  		case nil:
   178  			n++
   179  			continue
   180  		case driver.ErrRemoveArgument:
   181  			nvargs = nvargs[:len(nvargs)-1]
   182  			continue
   183  		case driver.ErrSkip:
   184  			if nextCC {
   185  				nextCC = false
   186  				checker = cc.CheckNamedValue
   187  			} else {
   188  				checker = defaultCheckNamedValue
   189  			}
   190  			goto nextCheck
   191  		default:
   192  			return nil, fmt.Errorf("sql: converting argument %s type: %v", describeNamedValue(nv), err)
   193  		}
   194  	}
   195  
   196  	// Check the length of arguments after conversion to allow for omitted
   197  	// arguments.
   198  	if want != -1 && len(nvargs) != want {
   199  		return nil, fmt.Errorf("sql: expected %d arguments, got %d", want, len(nvargs))
   200  	}
   201  
   202  	return nvargs, nil
   203  
   204  }
   205  
   206  // convertAssign is the same as convertAssignRows, but without the optional
   207  // rows argument.
   208  func convertAssign(dest, src interface{}) error {
   209  	return convertAssignRows(dest, src, nil)
   210  }
   211  
   212  // convertAssignRows copies to dest the value in src, converting it if possible.
   213  // An error is returned if the copy would result in loss of information.
   214  // dest should be a pointer type. If rows is passed in, the rows will
   215  // be used as the parent for any cursor values converted from a
   216  // driver.Rows to a *Rows.
   217  func convertAssignRows(dest, src interface{}, rows *Rows) error {
   218  	// Common cases, without reflect.
   219  	switch s := src.(type) {
   220  	case string:
   221  		switch d := dest.(type) {
   222  		case *string:
   223  			if d == nil {
   224  				return errNilPtr
   225  			}
   226  			*d = s
   227  			return nil
   228  		case *[]byte:
   229  			if d == nil {
   230  				return errNilPtr
   231  			}
   232  			*d = []byte(s)
   233  			return nil
   234  		case *RawBytes:
   235  			if d == nil {
   236  				return errNilPtr
   237  			}
   238  			*d = append((*d)[:0], s...)
   239  			return nil
   240  		}
   241  	case []byte:
   242  		switch d := dest.(type) {
   243  		case *string:
   244  			if d == nil {
   245  				return errNilPtr
   246  			}
   247  			*d = string(s)
   248  			return nil
   249  		case *interface{}:
   250  			if d == nil {
   251  				return errNilPtr
   252  			}
   253  			*d = cloneBytes(s)
   254  			return nil
   255  		case *[]byte:
   256  			if d == nil {
   257  				return errNilPtr
   258  			}
   259  			*d = cloneBytes(s)
   260  			return nil
   261  		case *RawBytes:
   262  			if d == nil {
   263  				return errNilPtr
   264  			}
   265  			*d = s
   266  			return nil
   267  		}
   268  	case time.Time:
   269  		switch d := dest.(type) {
   270  		case *time.Time:
   271  			*d = s
   272  			return nil
   273  		case *string:
   274  			*d = s.Format(time.RFC3339Nano)
   275  			return nil
   276  		case *[]byte:
   277  			if d == nil {
   278  				return errNilPtr
   279  			}
   280  			*d = []byte(s.Format(time.RFC3339Nano))
   281  			return nil
   282  		case *RawBytes:
   283  			if d == nil {
   284  				return errNilPtr
   285  			}
   286  			*d = s.AppendFormat((*d)[:0], time.RFC3339Nano)
   287  			return nil
   288  		}
   289  	case nil:
   290  		switch d := dest.(type) {
   291  		case *interface{}:
   292  			if d == nil {
   293  				return errNilPtr
   294  			}
   295  			*d = nil
   296  			return nil
   297  		case *[]byte:
   298  			if d == nil {
   299  				return errNilPtr
   300  			}
   301  			*d = nil
   302  			return nil
   303  		case *RawBytes:
   304  			if d == nil {
   305  				return errNilPtr
   306  			}
   307  			*d = nil
   308  			return nil
   309  		}
   310  	// The driver is returning a cursor the client may iterate over.
   311  	case driver.Rows:
   312  		switch d := dest.(type) {
   313  		case *Rows:
   314  			if d == nil {
   315  				return errNilPtr
   316  			}
   317  			if rows == nil {
   318  				return errors.New("invalid context to convert cursor rows, missing parent *Rows")
   319  			}
   320  			rows.closemu.Lock()
   321  			*d = Rows{
   322  				dc:          rows.dc,
   323  				releaseConn: func(error) {},
   324  				rowsi:       s,
   325  			}
   326  			// Chain the cancel function.
   327  			parentCancel := rows.cancel
   328  			rows.cancel = func() {
   329  				// When Rows.cancel is called, the closemu will be locked as well.
   330  				// So we can access rs.lasterr.
   331  				d.close(rows.lasterr)
   332  				if parentCancel != nil {
   333  					parentCancel()
   334  				}
   335  			}
   336  			rows.closemu.Unlock()
   337  			return nil
   338  		}
   339  	}
   340  
   341  	var sv reflect.Value
   342  
   343  	switch d := dest.(type) {
   344  	case *string:
   345  		sv = reflect.ValueOf(src)
   346  		switch sv.Kind() {
   347  		case reflect.Bool,
   348  			reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
   349  			reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
   350  			reflect.Float32, reflect.Float64:
   351  			*d = asString(src)
   352  			return nil
   353  		}
   354  	case *[]byte:
   355  		sv = reflect.ValueOf(src)
   356  		if b, ok := asBytes(nil, sv); ok {
   357  			*d = b
   358  			return nil
   359  		}
   360  	case *RawBytes:
   361  		sv = reflect.ValueOf(src)
   362  		if b, ok := asBytes([]byte(*d)[:0], sv); ok {
   363  			*d = RawBytes(b)
   364  			return nil
   365  		}
   366  	case *bool:
   367  		bv, err := driver.Bool.ConvertValue(src)
   368  		if err == nil {
   369  			*d = bv.(bool)
   370  		}
   371  		return err
   372  	case *interface{}:
   373  		*d = src
   374  		return nil
   375  	}
   376  
   377  	if scanner, ok := dest.(Scanner); ok {
   378  		return scanner.Scan(src)
   379  	}
   380  
   381  	dpv := reflect.ValueOf(dest)
   382  	if dpv.Kind() != reflect.Ptr {
   383  		return errors.New("destination not a pointer")
   384  	}
   385  	if dpv.IsNil() {
   386  		return errNilPtr
   387  	}
   388  
   389  	if !sv.IsValid() {
   390  		sv = reflect.ValueOf(src)
   391  	}
   392  
   393  	dv := reflect.Indirect(dpv)
   394  	if sv.IsValid() && sv.Type().AssignableTo(dv.Type()) {
   395  		switch b := src.(type) {
   396  		case []byte:
   397  			dv.Set(reflect.ValueOf(cloneBytes(b)))
   398  		default:
   399  			dv.Set(sv)
   400  		}
   401  		return nil
   402  	}
   403  
   404  	if dv.Kind() == sv.Kind() && sv.Type().ConvertibleTo(dv.Type()) {
   405  		dv.Set(sv.Convert(dv.Type()))
   406  		return nil
   407  	}
   408  
   409  	// The following conversions use a string value as an intermediate representation
   410  	// to convert between various numeric types.
   411  	//
   412  	// This also allows scanning into user defined types such as "type Int int64".
   413  	// For symmetry, also check for string destination types.
   414  	switch dv.Kind() {
   415  	case reflect.Ptr:
   416  		if src == nil {
   417  			dv.Set(reflect.Zero(dv.Type()))
   418  			return nil
   419  		}
   420  		dv.Set(reflect.New(dv.Type().Elem()))
   421  		return convertAssignRows(dv.Interface(), src, rows)
   422  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   423  		s := asString(src)
   424  		i64, err := strconv.ParseInt(s, 10, dv.Type().Bits())
   425  		if err != nil {
   426  			err = strconvErr(err)
   427  			return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, dv.Kind(), err)
   428  		}
   429  		dv.SetInt(i64)
   430  		return nil
   431  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
   432  		s := asString(src)
   433  		u64, err := strconv.ParseUint(s, 10, dv.Type().Bits())
   434  		if err != nil {
   435  			err = strconvErr(err)
   436  			return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, dv.Kind(), err)
   437  		}
   438  		dv.SetUint(u64)
   439  		return nil
   440  	case reflect.Float32, reflect.Float64:
   441  		s := asString(src)
   442  		f64, err := strconv.ParseFloat(s, dv.Type().Bits())
   443  		if err != nil {
   444  			err = strconvErr(err)
   445  			return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, dv.Kind(), err)
   446  		}
   447  		dv.SetFloat(f64)
   448  		return nil
   449  	case reflect.String:
   450  		switch v := src.(type) {
   451  		case string:
   452  			dv.SetString(v)
   453  			return nil
   454  		case []byte:
   455  			dv.SetString(string(v))
   456  			return nil
   457  		}
   458  	}
   459  
   460  	return fmt.Errorf("unsupported Scan, storing driver.Value type %T into type %T", src, dest)
   461  }
   462  
   463  func strconvErr(err error) error {
   464  	if ne, ok := err.(*strconv.NumError); ok {
   465  		return ne.Err
   466  	}
   467  	return err
   468  }
   469  
   470  func cloneBytes(b []byte) []byte {
   471  	if b == nil {
   472  		return nil
   473  	}
   474  	c := make([]byte, len(b))
   475  	copy(c, b)
   476  	return c
   477  }
   478  
   479  func asString(src interface{}) string {
   480  	switch v := src.(type) {
   481  	case string:
   482  		return v
   483  	case []byte:
   484  		return string(v)
   485  	}
   486  	rv := reflect.ValueOf(src)
   487  	switch rv.Kind() {
   488  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   489  		return strconv.FormatInt(rv.Int(), 10)
   490  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
   491  		return strconv.FormatUint(rv.Uint(), 10)
   492  	case reflect.Float64:
   493  		return strconv.FormatFloat(rv.Float(), 'g', -1, 64)
   494  	case reflect.Float32:
   495  		return strconv.FormatFloat(rv.Float(), 'g', -1, 32)
   496  	case reflect.Bool:
   497  		return strconv.FormatBool(rv.Bool())
   498  	}
   499  	return fmt.Sprintf("%v", src)
   500  }
   501  
   502  func asBytes(buf []byte, rv reflect.Value) (b []byte, ok bool) {
   503  	switch rv.Kind() {
   504  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   505  		return strconv.AppendInt(buf, rv.Int(), 10), true
   506  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
   507  		return strconv.AppendUint(buf, rv.Uint(), 10), true
   508  	case reflect.Float32:
   509  		return strconv.AppendFloat(buf, rv.Float(), 'g', -1, 32), true
   510  	case reflect.Float64:
   511  		return strconv.AppendFloat(buf, rv.Float(), 'g', -1, 64), true
   512  	case reflect.Bool:
   513  		return strconv.AppendBool(buf, rv.Bool()), true
   514  	case reflect.String:
   515  		s := rv.String()
   516  		return append(buf, s...), true
   517  	}
   518  	return
   519  }
   520  
   521  var valuerReflectType = reflect.TypeOf((*driver.Valuer)(nil)).Elem()
   522  
   523  // callValuerValue returns vr.Value(), with one exception:
   524  // If vr.Value is an auto-generated method on a pointer type and the
   525  // pointer is nil, it would panic at runtime in the panicwrap
   526  // method. Treat it like nil instead.
   527  // Issue 8415.
   528  //
   529  // This is so people can implement driver.Value on value types and
   530  // still use nil pointers to those types to mean nil/NULL, just like
   531  // string/*string.
   532  //
   533  // This function is mirrored in the database/sql/driver package.
   534  func callValuerValue(vr driver.Valuer) (v driver.Value, err error) {
   535  	if rv := reflect.ValueOf(vr); rv.Kind() == reflect.Ptr &&
   536  		rv.IsNil() &&
   537  		rv.Type().Elem().Implements(valuerReflectType) {
   538  		return nil, nil
   539  	}
   540  	return vr.Value()
   541  }
   542  

View as plain text