// Copyright 2011 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.// Type conversions for Scan.package sqlimport (_// for linkname)varerrNilPtr = errors.New("destination pointer is nil") // embedded in descriptive errorfunc ( *driver.NamedValue) string {iflen(.Name) == 0 {returnfmt.Sprintf("$%d", .Ordinal) }returnfmt.Sprintf("with name %q", .Name)}func ( string) error {iflen() == 0 {returnnil } , := utf8.DecodeRuneInString()ifunicode.IsLetter() {returnnil }returnfmt.Errorf("name %q does not begin with a letter", )}// ccChecker wraps the driver.ColumnConverter and allows it to be used// as if it were a NamedValueChecker. If the driver ColumnConverter// is not present then the NamedValueChecker will return driver.ErrSkip.typeccCheckerstruct {ccidriver.ColumnConverterwantint}func ( ccChecker) ( *driver.NamedValue) error {if .cci == nil {returndriver.ErrSkip }// The column converter shouldn't be called on any index // it isn't expecting. The final error will be thrown // in the argument converter loop. := .Ordinal - 1if .want >= 0 && .want <= {returnnil }// First, see if the value itself knows how to convert // itself to a driver type. For example, a NullString // struct changing into a string or nil.if , := .Value.(driver.Valuer); { , := callValuerValue()if != nil {return }if !driver.IsValue() {returnfmt.Errorf("non-subset type %T returned from Value", ) } .Value = }// Second, ask the column to sanity check itself. For // example, drivers might use this to make sure that // an int64 values being inserted into a 16-bit // integer field is in range (before getting // truncated), or that a nil can't go into a NOT NULL // column before going across the network to get the // same error.varerror := .Value .Value, = .cci.ColumnConverter().ConvertValue()if != nil {return }if !driver.IsValue(.Value) {returnfmt.Errorf("driver ColumnConverter error converted %T to unsupported type %T", , .Value) }returnnil}// defaultCheckNamedValue wraps the default ColumnConverter to have the same// function signature as the CheckNamedValue in the driver.NamedValueChecker// interface.func ( *driver.NamedValue) ( error) { .Value, = driver.DefaultParameterConverter.ConvertValue(.Value)return}// driverArgsConnLocked converts arguments from callers of Stmt.Exec and// Stmt.Query into driver Values.//// The statement ds may be nil, if no statement is available.//// ci must be locked.func ( driver.Conn, *driverStmt, []any) ([]driver.NamedValue, error) { := make([]driver.NamedValue, len())// -1 means the driver doesn't know how to count the number of // placeholders, so we won't sanity check input here and instead let the // driver deal with errors. := -1vardriver.StmtvarccCheckerif != nil { = .si = .si.NumInput() .want = }// Check all types of interfaces from the start. // Drivers may opt to use the NamedValueChecker for special // argument types, then return driver.ErrSkip to pass it along // to the column converter. , := .(driver.NamedValueChecker)if ! { , _ = .(driver.NamedValueChecker) } , := .(driver.ColumnConverter)if { .cci = }// Loop through all the arguments, checking each one. // If no error is returned simply increment the index // and continue. However, if driver.ErrRemoveArgument // is returned the argument is not included in the query // argument list.varerrorvarintfor , := range { := &[]if , := .(NamedArg); {if = validateNamedValueName(.Name); != nil {returnnil, } = .Value .Name = .Name } .Ordinal = + 1 .Value = // Checking sequence has four routes: // A: 1. Default // B: 1. NamedValueChecker 2. Column Converter 3. Default // C: 1. NamedValueChecker 3. Default // D: 1. Column Converter 2. Default // // The only time a Column Converter is called is first // or after NamedValueConverter. If first it is handled before // the nextCheck label. Thus for repeats tries only when the // NamedValueConverter is selected should the Column Converter // be used in the retry. := defaultCheckNamedValue := falseswitch {case != nil: = != nil = .CheckNamedValuecase != nil: = .CheckNamedValue } : = ()switch {casenil: ++continuecasedriver.ErrRemoveArgument: = [:len()-1]continuecasedriver.ErrSkip:if { = false = .CheckNamedValue } else { = defaultCheckNamedValue }gotodefault:returnnil, fmt.Errorf("sql: converting argument %s type: %w", describeNamedValue(), ) } }// Check the length of arguments after conversion to allow for omitted // arguments.if != -1 && len() != {returnnil, fmt.Errorf("sql: expected %d arguments, got %d", , len()) }return , nil}// convertAssign is the same as convertAssignRows, but without the optional// rows argument.//// convertAssign should be an internal detail,// but widely used packages access it using linkname.// Notable members of the hall of shame include:// - ariga.io/entcache//// Do not remove or change the type signature.// See go.dev/issue/67401.////go:linkname convertAssignfunc ( any, any) error {returnconvertAssignRows(, , nil)}// ConvertAssign copies the value in src to the value pointed at by dest.// See the documentation on [Rows.Scan] for details on conversions.// dest must be a pointer or must implement [Scanner].//// Implementations of [driver.RowsColumnScanner] should pass through// their [driver.ScanContext] parameter.// In other cases, pass driver.ScanContext{} as the context.//// ConvertAssign is intended for use by driver implementations.// Most users should not need to use it directly.func ( driver.ScanContext, any, driver.Value) error { , := internal.ScanContextValue(internal.ScanContext()).(*Rows)returnconvertAssignRows(, , )}// convertAssignRows copies to dest the value in src, converting it if possible.// An error is returned if the copy would result in loss of information.// dest should be a pointer type. If rows is passed in, the rows will// be used as the parent for any cursor values converted from a// driver.Rows to a *Rows.func (, any, *Rows) error {// Common cases, without reflect.switch s := .(type) {casestring:switch d := .(type) {case *string:if == nil {returnerrNilPtr } * = returnnilcase *[]byte:if == nil {returnerrNilPtr } * = []byte()returnnilcase *RawBytes:if == nil {returnerrNilPtr } * = .setrawbuf(append(.rawbuf(), ...))returnnilcase *uuid.UUID:if == nil {returnerrNilPtr } , := uuid.Parse()if != nil {returnfmt.Errorf("converting driver.Value type string (%q) to a UUID: %v", , ) } * = returnnil }case []byte:switch d := .(type) {case *string:if == nil {returnerrNilPtr } * = string()returnnilcase *any:if == nil {returnerrNilPtr } * = bytes.Clone()returnnilcase *[]byte:if == nil {returnerrNilPtr } * = bytes.Clone()returnnilcase *RawBytes:if == nil {returnerrNilPtr } * = returnnilcase *uuid.UUID:if == nil {returnerrNilPtr }iflen() == len(*) {copy((*)[:], )returnnil }varuuid.UUID := .UnmarshalText()if != nil {returnfmt.Errorf("converting driver.Value type []byte (%q) to a UUID: %v", , ) } * = returnnil }casetime.Time:switch d := .(type) {case *time.Time: * = returnnilcase *string: * = .Format(time.RFC3339Nano)returnnilcase *[]byte:if == nil {returnerrNilPtr } * = .AppendFormat(make([]byte, 0, len(time.RFC3339Nano)), time.RFC3339Nano)returnnilcase *RawBytes:if == nil {returnerrNilPtr } * = .setrawbuf(.AppendFormat(.rawbuf(), time.RFC3339Nano))returnnil }casedecimalDecompose:switch d := .(type) {casedecimalCompose:return .Compose(.Decompose(nil)) }casenil:switch d := .(type) {case *any:if == nil {returnerrNilPtr } * = nilreturnnilcase *[]byte:if == nil {returnerrNilPtr } * = nilreturnnilcase *RawBytes:if == nil {returnerrNilPtr } * = nilreturnnil }// The driver is returning a cursor the client may iterate over.casedriver.Rows: , := .(*Rows)if {if == nil {returnerrNilPtr }if == nil {returnerrors.New("invalid context to convert cursor rows, missing parent *Rows") }// This is hazardous and not really correct: If the user provides us // with the same *Rows for each Scan (which they very likely will), // then this overwrites the previously-used Rows, including its mutexes. // The chained row cancel function below will also repeatedly reference // the same *Rows. * = Rows{dc: .dc,releaseConn: func(error) {},rowsi: , }// Chain the cancel function. // // This has problems: // - Repeatedly wrapping the cancel func is inefficient compared to // just storing a []*Rows of children. // - The cancel func is wrapped for each cursor read. If we scan N // rows, each with a child cursor, we end up with N chained cancel // funcs. (Also, if the user is reusing a Rows--see above--the cancel // funcs might all be referencing the same underlying Rows cursor.) // - It seems like it would be reasonable to invalidate a cursor // after advancing to the next parent row (the row which contains // the cursor). We don't do that now, and it isn't clear that we can // change this. := .cancel .cancel = func() {// When Rows.cancel is called, the closemu will be locked as well. // So we can access rows.lasterr. .close(.lasterr)if != nil { () } }returnnil } }varreflect.Valueswitch d := .(type) {case *string: = reflect.ValueOf()switch .Kind() {casereflect.Bool,reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,reflect.Float32, reflect.Float64: * = asString()returnnil }case *[]byte: = reflect.ValueOf()if , := asBytes(nil, ); { * = returnnil }case *RawBytes: = reflect.ValueOf()if , := asBytes(.rawbuf(), ); { * = .setrawbuf()returnnil }case *bool: , := driver.Bool.ConvertValue()if == nil { * = .(bool) }returncase *any: * = returnnil }if , := .(Scanner); {return .Scan() } := reflect.ValueOf()if .Kind() != reflect.Pointer {returnerrors.New("destination not a pointer") }if .IsNil() {returnerrNilPtr }if !.IsValid() { = reflect.ValueOf() } := reflect.Indirect()if .IsValid() && .Type().AssignableTo(.Type()) {switch b := .(type) {case []byte: .Set(reflect.ValueOf(bytes.Clone()))default: .Set() }returnnil }if .Kind() == .Kind() && .Type().ConvertibleTo(.Type()) { .Set(.Convert(.Type()))returnnil }// The following conversions use a string value as an intermediate representation // to convert between various numeric types. // // This also allows scanning into user defined types such as "type Int int64". // For symmetry, also check for string destination types.switch .Kind() {casereflect.Pointer:if == nil { .SetZero()returnnil } .Set(reflect.New(.Type().Elem()))return (.Interface(), , )casereflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:if == nil {returnfmt.Errorf("converting NULL to %s is unsupported", .Kind()) } := asString() , := strconv.ParseInt(, 10, .Type().Bits())if != nil { = strconvErr()returnfmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", , , .Kind(), ) } .SetInt()returnnilcasereflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:if == nil {returnfmt.Errorf("converting NULL to %s is unsupported", .Kind()) } := asString() , := strconv.ParseUint(, 10, .Type().Bits())if != nil { = strconvErr()returnfmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", , , .Kind(), ) } .SetUint()returnnilcasereflect.Float32, reflect.Float64:if == nil {returnfmt.Errorf("converting NULL to %s is unsupported", .Kind()) } := asString() , := strconv.ParseFloat(, .Type().Bits())if != nil { = strconvErr()returnfmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", , , .Kind(), ) } .SetFloat()returnnilcasereflect.String:if == nil {returnfmt.Errorf("converting NULL to %s is unsupported", .Kind()) }switch v := .(type) {casestring: .SetString()returnnilcase []byte: .SetString(string())returnnil } }returnfmt.Errorf("unsupported Scan, storing driver.Value type %T into type %T", , )}func ( error) error {if , := .(*strconv.NumError); {return .Err }return}func ( any) string {switch v := .(type) {casestring:returncase []byte:returnstring() } := reflect.ValueOf()switch .Kind() {casereflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:returnstrconv.FormatInt(.Int(), 10)casereflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:returnstrconv.FormatUint(.Uint(), 10)casereflect.Float64:returnstrconv.FormatFloat(.Float(), 'g', -1, 64)casereflect.Float32:returnstrconv.FormatFloat(.Float(), 'g', -1, 32)casereflect.Bool:returnstrconv.FormatBool(.Bool()) }returnfmt.Sprintf("%v", )}func ( []byte, reflect.Value) ( []byte, bool) {switch .Kind() {casereflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:returnstrconv.AppendInt(, .Int(), 10), truecasereflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:returnstrconv.AppendUint(, .Uint(), 10), truecasereflect.Float32:returnstrconv.AppendFloat(, .Float(), 'g', -1, 32), truecasereflect.Float64:returnstrconv.AppendFloat(, .Float(), 'g', -1, 64), truecasereflect.Bool:returnstrconv.AppendBool(, .Bool()), truecasereflect.String: := .String()returnappend(, ...), true }return}varvaluerReflectType = reflect.TypeFor[driver.Valuer]()// callValuerValue returns vr.Value(), with one exception:// If vr.Value is an auto-generated method on a pointer type and the// pointer is nil, it would panic at runtime in the panicwrap// method. Treat it like nil instead.// Issue 8415.//// This is so people can implement driver.Value on value types and// still use nil pointers to those types to mean nil/NULL, just like// string/*string.//// This function is mirrored in the database/sql/driver package.func ( driver.Valuer) ( driver.Value, error) {if := reflect.ValueOf(); .Kind() == reflect.Pointer && .IsNil() && .Type().Elem().Implements(valuerReflectType) {returnnil, nil }return .Value()}// decimal composes or decomposes a decimal value to and from individual parts.// There are four parts: a boolean negative flag, a form byte with three possible states// (finite=0, infinite=1, NaN=2), a base-2 big-endian integer// coefficient (also known as a significand) as a []byte, and an int32 exponent.// These are composed into a final value as "decimal = (neg) (form=finite) coefficient * 10 ^ exponent".// A zero length coefficient is a zero value.// The big-endian integer coefficient stores the most significant byte first (at coefficient[0]).// If the form is not finite the coefficient and exponent should be ignored.// The negative parameter may be set to true for any form, although implementations are not required// to respect the negative parameter in the non-finite form.//// Implementations may choose to set the negative parameter to true on a zero or NaN value,// but implementations that do not differentiate between negative and positive// zero or NaN values should ignore the negative parameter without error.// If an implementation does not support Infinity it may be converted into a NaN without error.// If a value is set that is larger than what is supported by an implementation,// an error must be returned.// Implementations must return an error if a NaN or Infinity is attempted to be set while neither// are supported.//// NOTE(kardianos): This is an experimental interface. See https://golang.org/issue/30870typedecimalinterface {decimalDecomposedecimalCompose}typedecimalDecomposeinterface {// Decompose returns the internal decimal state in parts. // If the provided buf has sufficient capacity, buf may be returned as the coefficient with // the value set and length set as appropriate.Decompose(buf []byte) (form byte, negative bool, coefficient []byte, exponent int32)}typedecimalComposeinterface {// Compose sets the internal decimal value from parts. If the value cannot be // represented then an error should be returned.Compose(form byte, negative bool, coefficient []byte, exponent int32) error}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)