Source file src/database/sql/convert_test.go

     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  package sql
     6  
     7  import (
     8  	"database/sql/driver"
     9  	"fmt"
    10  	"internal/asan"
    11  	"reflect"
    12  	"runtime"
    13  	"strings"
    14  	"sync"
    15  	"testing"
    16  	"time"
    17  	"uuid"
    18  )
    19  
    20  var someTime = time.Unix(123, 0)
    21  var answer int64 = 42
    22  
    23  type (
    24  	userDefined       float64
    25  	userDefinedSlice  []int
    26  	userDefinedString string
    27  )
    28  
    29  type conversionTest struct {
    30  	s, d any // source and destination
    31  
    32  	// following are used if they're non-zero
    33  	wantint    int64
    34  	wantuint   uint64
    35  	wantstr    string
    36  	wantbytes  []byte
    37  	wantraw    RawBytes
    38  	wantf32    float32
    39  	wantf64    float64
    40  	wanttime   time.Time
    41  	wantbool   bool // used if d is of type *bool
    42  	wantuuid   uuid.UUID
    43  	wanterr    string
    44  	wantiface  any
    45  	wantptr    *int64 // if non-nil, *d's pointed value must be equal to *wantptr
    46  	wantnil    bool   // if true, *d must be *int64(nil)
    47  	wantusrdef userDefined
    48  	wantusrstr userDefinedString
    49  }
    50  
    51  // Target variables for scanning into.
    52  var (
    53  	scanstr    string
    54  	scanbytes  []byte
    55  	scanraw    RawBytes
    56  	scanint    int
    57  	scanuint8  uint8
    58  	scanuint16 uint16
    59  	scanbool   bool
    60  	scanf32    float32
    61  	scanf64    float64
    62  	scantime   time.Time
    63  	scanuuid   uuid.UUID
    64  	scanptr    *int64
    65  	scaniface  any
    66  )
    67  
    68  func conversionTests() []conversionTest {
    69  	// Return a fresh instance to test so "go test -count 2" works correctly.
    70  	return []conversionTest{
    71  		// Exact conversions (destination pointer type matches source type)
    72  		{s: "foo", d: &scanstr, wantstr: "foo"},
    73  		{s: 123, d: &scanint, wantint: 123},
    74  		{s: someTime, d: &scantime, wanttime: someTime},
    75  
    76  		// To strings
    77  		{s: "string", d: &scanstr, wantstr: "string"},
    78  		{s: []byte("byteslice"), d: &scanstr, wantstr: "byteslice"},
    79  		{s: 123, d: &scanstr, wantstr: "123"},
    80  		{s: int8(123), d: &scanstr, wantstr: "123"},
    81  		{s: int64(123), d: &scanstr, wantstr: "123"},
    82  		{s: uint8(123), d: &scanstr, wantstr: "123"},
    83  		{s: uint16(123), d: &scanstr, wantstr: "123"},
    84  		{s: uint32(123), d: &scanstr, wantstr: "123"},
    85  		{s: uint64(123), d: &scanstr, wantstr: "123"},
    86  		{s: 1.5, d: &scanstr, wantstr: "1.5"},
    87  
    88  		// From time.Time:
    89  		{s: time.Unix(1, 0).UTC(), d: &scanstr, wantstr: "1970-01-01T00:00:01Z"},
    90  		{s: time.Unix(1453874597, 0).In(time.FixedZone("here", -3600*8)), d: &scanstr, wantstr: "2016-01-26T22:03:17-08:00"},
    91  		{s: time.Unix(1, 2).UTC(), d: &scanstr, wantstr: "1970-01-01T00:00:01.000000002Z"},
    92  		{s: time.Time{}, d: &scanstr, wantstr: "0001-01-01T00:00:00Z"},
    93  		{s: time.Unix(1, 2).UTC(), d: &scanbytes, wantbytes: []byte("1970-01-01T00:00:01.000000002Z")},
    94  		{s: time.Unix(1, 2).UTC(), d: &scaniface, wantiface: time.Unix(1, 2).UTC()},
    95  
    96  		// To []byte
    97  		{s: nil, d: &scanbytes, wantbytes: nil},
    98  		{s: "string", d: &scanbytes, wantbytes: []byte("string")},
    99  		{s: []byte("byteslice"), d: &scanbytes, wantbytes: []byte("byteslice")},
   100  		{s: 123, d: &scanbytes, wantbytes: []byte("123")},
   101  		{s: int8(123), d: &scanbytes, wantbytes: []byte("123")},
   102  		{s: int64(123), d: &scanbytes, wantbytes: []byte("123")},
   103  		{s: uint8(123), d: &scanbytes, wantbytes: []byte("123")},
   104  		{s: uint16(123), d: &scanbytes, wantbytes: []byte("123")},
   105  		{s: uint32(123), d: &scanbytes, wantbytes: []byte("123")},
   106  		{s: uint64(123), d: &scanbytes, wantbytes: []byte("123")},
   107  		{s: 1.5, d: &scanbytes, wantbytes: []byte("1.5")},
   108  
   109  		// To RawBytes
   110  		{s: nil, d: &scanraw, wantraw: nil},
   111  		{s: []byte("byteslice"), d: &scanraw, wantraw: RawBytes("byteslice")},
   112  		{s: "string", d: &scanraw, wantraw: RawBytes("string")},
   113  		{s: 123, d: &scanraw, wantraw: RawBytes("123")},
   114  		{s: int8(123), d: &scanraw, wantraw: RawBytes("123")},
   115  		{s: int64(123), d: &scanraw, wantraw: RawBytes("123")},
   116  		{s: uint8(123), d: &scanraw, wantraw: RawBytes("123")},
   117  		{s: uint16(123), d: &scanraw, wantraw: RawBytes("123")},
   118  		{s: uint32(123), d: &scanraw, wantraw: RawBytes("123")},
   119  		{s: uint64(123), d: &scanraw, wantraw: RawBytes("123")},
   120  		{s: 1.5, d: &scanraw, wantraw: RawBytes("1.5")},
   121  		// time.Time has been placed here to check that the RawBytes slice gets
   122  		// correctly reset when calling time.Time.AppendFormat.
   123  		{s: time.Unix(2, 5).UTC(), d: &scanraw, wantraw: RawBytes("1970-01-01T00:00:02.000000005Z")},
   124  
   125  		// Strings to integers
   126  		{s: "255", d: &scanuint8, wantuint: 255},
   127  		{s: "256", d: &scanuint8, wanterr: "converting driver.Value type string (\"256\") to a uint8: value out of range"},
   128  		{s: "256", d: &scanuint16, wantuint: 256},
   129  		{s: "-1", d: &scanint, wantint: -1},
   130  		{s: "foo", d: &scanint, wanterr: "converting driver.Value type string (\"foo\") to a int: invalid syntax"},
   131  
   132  		// int64 to smaller integers
   133  		{s: int64(5), d: &scanuint8, wantuint: 5},
   134  		{s: int64(256), d: &scanuint8, wanterr: "converting driver.Value type int64 (\"256\") to a uint8: value out of range"},
   135  		{s: int64(256), d: &scanuint16, wantuint: 256},
   136  		{s: int64(65536), d: &scanuint16, wanterr: "converting driver.Value type int64 (\"65536\") to a uint16: value out of range"},
   137  
   138  		// True bools
   139  		{s: true, d: &scanbool, wantbool: true},
   140  		{s: "True", d: &scanbool, wantbool: true},
   141  		{s: "TRUE", d: &scanbool, wantbool: true},
   142  		{s: "1", d: &scanbool, wantbool: true},
   143  		{s: 1, d: &scanbool, wantbool: true},
   144  		{s: int64(1), d: &scanbool, wantbool: true},
   145  		{s: uint16(1), d: &scanbool, wantbool: true},
   146  
   147  		// False bools
   148  		{s: false, d: &scanbool, wantbool: false},
   149  		{s: "false", d: &scanbool, wantbool: false},
   150  		{s: "FALSE", d: &scanbool, wantbool: false},
   151  		{s: "0", d: &scanbool, wantbool: false},
   152  		{s: 0, d: &scanbool, wantbool: false},
   153  		{s: int64(0), d: &scanbool, wantbool: false},
   154  		{s: uint16(0), d: &scanbool, wantbool: false},
   155  
   156  		// Not bools
   157  		{s: "yup", d: &scanbool, wanterr: `sql/driver: couldn't convert "yup" into type bool`},
   158  		{s: 2, d: &scanbool, wanterr: `sql/driver: couldn't convert 2 into type bool`},
   159  
   160  		// Floats
   161  		{s: float64(1.5), d: &scanf64, wantf64: float64(1.5)},
   162  		{s: int64(1), d: &scanf64, wantf64: float64(1)},
   163  		{s: float64(1.5), d: &scanf32, wantf32: float32(1.5)},
   164  		{s: "1.5", d: &scanf32, wantf32: float32(1.5)},
   165  		{s: "1.5", d: &scanf64, wantf64: float64(1.5)},
   166  
   167  		// UUIDs
   168  		{s: "97b6a4e0-5323-43e9-82c8-88110d6686d6", d: &scanuuid, wantuuid: uuid.MustParse("97b6a4e0-5323-43e9-82c8-88110d6686d6")},
   169  		{s: "97B6A4E0-5323-43E9-82C8-88110D6686D6", d: &scanuuid, wantuuid: uuid.MustParse("97b6a4e0-5323-43e9-82c8-88110d6686d6")},
   170  		{s: "x", d: &scanuuid, wanterr: `converting driver.Value type string ("x") to a UUID: invalid uuid`},
   171  		{s: []byte("97b6a4e0-5323-43e9-82c8-88110d6686d6"), d: &scanuuid, wantuuid: uuid.MustParse("97b6a4e0-5323-43e9-82c8-88110d6686d6")},
   172  		{s: []byte("97B6A4E0-5323-43E9-82C8-88110D6686D6"), d: &scanuuid, wantuuid: uuid.MustParse("97b6a4e0-5323-43e9-82c8-88110d6686d6")},
   173  		{s: []byte{0x97, 0xb6, 0xa4, 0xe0, 0x53, 0x23, 0x43, 0xe9, 0x82, 0xc8, 0x88, 0x11, 0x0d, 0x66, 0x86, 0xd6}, d: &scanuuid, wantuuid: uuid.MustParse("97b6a4e0-5323-43e9-82c8-88110d6686d6")},
   174  		{s: []byte("x"), d: &scanuuid, wanterr: `converting driver.Value type []byte ("x") to a UUID: invalid uuid`},
   175  
   176  		// Pointers
   177  		{s: any(nil), d: &scanptr, wantnil: true},
   178  		{s: int64(42), d: &scanptr, wantptr: &answer},
   179  
   180  		// To interface{}
   181  		{s: float64(1.5), d: &scaniface, wantiface: float64(1.5)},
   182  		{s: int64(1), d: &scaniface, wantiface: int64(1)},
   183  		{s: "str", d: &scaniface, wantiface: "str"},
   184  		{s: []byte("byteslice"), d: &scaniface, wantiface: []byte("byteslice")},
   185  		{s: true, d: &scaniface, wantiface: true},
   186  		{s: nil, d: &scaniface},
   187  		{s: []byte(nil), d: &scaniface, wantiface: []byte(nil)},
   188  
   189  		// To a user-defined type
   190  		{s: 1.5, d: new(userDefined), wantusrdef: 1.5},
   191  		{s: int64(123), d: new(userDefined), wantusrdef: 123},
   192  		{s: "1.5", d: new(userDefined), wantusrdef: 1.5},
   193  		{s: []byte{1, 2, 3}, d: new(userDefinedSlice), wanterr: `unsupported Scan, storing driver.Value type []uint8 into type *sql.userDefinedSlice`},
   194  		{s: "str", d: new(userDefinedString), wantusrstr: "str"},
   195  
   196  		// Other errors
   197  		{s: complex(1, 2), d: &scanstr, wanterr: `unsupported Scan, storing driver.Value type complex128 into type *string`},
   198  	}
   199  }
   200  
   201  func intPtrValue(intptr any) any {
   202  	return reflect.Indirect(reflect.Indirect(reflect.ValueOf(intptr))).Int()
   203  }
   204  
   205  func intValue(intptr any) int64 {
   206  	return reflect.Indirect(reflect.ValueOf(intptr)).Int()
   207  }
   208  
   209  func uintValue(intptr any) uint64 {
   210  	return reflect.Indirect(reflect.ValueOf(intptr)).Uint()
   211  }
   212  
   213  func float64Value(ptr any) float64 {
   214  	return *(ptr.(*float64))
   215  }
   216  
   217  func float32Value(ptr any) float32 {
   218  	return *(ptr.(*float32))
   219  }
   220  
   221  func timeValue(ptr any) time.Time {
   222  	return *(ptr.(*time.Time))
   223  }
   224  
   225  func uuidValue(ptr any) uuid.UUID {
   226  	return *(ptr.(*uuid.UUID))
   227  }
   228  
   229  func TestConversions(t *testing.T) {
   230  	for n, ct := range conversionTests() {
   231  		err := convertAssign(ct.d, ct.s)
   232  		errstr := ""
   233  		if err != nil {
   234  			errstr = err.Error()
   235  		}
   236  		errf := func(format string, args ...any) {
   237  			base := fmt.Sprintf("convertAssign #%d: for %v (%T) -> %T, ", n, ct.s, ct.s, ct.d)
   238  			t.Errorf(base+format, args...)
   239  		}
   240  		if errstr != ct.wanterr {
   241  			errf("got error %q, want error %q", errstr, ct.wanterr)
   242  		}
   243  		if ct.wantstr != "" && ct.wantstr != scanstr {
   244  			errf("want string %q, got %q", ct.wantstr, scanstr)
   245  		}
   246  		if ct.wantbytes != nil && string(ct.wantbytes) != string(scanbytes) {
   247  			errf("want byte %q, got %q", ct.wantbytes, scanbytes)
   248  		}
   249  		if ct.wantraw != nil && string(ct.wantraw) != string(scanraw) {
   250  			errf("want RawBytes %q, got %q", ct.wantraw, scanraw)
   251  		}
   252  		if ct.wantint != 0 && ct.wantint != intValue(ct.d) {
   253  			errf("want int %d, got %d", ct.wantint, intValue(ct.d))
   254  		}
   255  		if ct.wantuint != 0 && ct.wantuint != uintValue(ct.d) {
   256  			errf("want uint %d, got %d", ct.wantuint, uintValue(ct.d))
   257  		}
   258  		if ct.wantf32 != 0 && ct.wantf32 != float32Value(ct.d) {
   259  			errf("want float32 %v, got %v", ct.wantf32, float32Value(ct.d))
   260  		}
   261  		if ct.wantf64 != 0 && ct.wantf64 != float64Value(ct.d) {
   262  			errf("want float32 %v, got %v", ct.wantf64, float64Value(ct.d))
   263  		}
   264  		if bp, boolTest := ct.d.(*bool); boolTest && *bp != ct.wantbool && ct.wanterr == "" {
   265  			errf("want bool %v, got %v", ct.wantbool, *bp)
   266  		}
   267  		if !ct.wanttime.IsZero() && !ct.wanttime.Equal(timeValue(ct.d)) {
   268  			errf("want time %v, got %v", ct.wanttime, timeValue(ct.d))
   269  		}
   270  		if ct.wantuuid != (uuid.UUID{}) && ct.wantuuid != uuidValue(ct.d) {
   271  			errf("want uuid %v, got %v", ct.wantuuid, uuidValue(ct.d))
   272  		}
   273  		if ct.wantnil && *ct.d.(**int64) != nil {
   274  			errf("want nil, got %v", intPtrValue(ct.d))
   275  		}
   276  		if ct.wantptr != nil {
   277  			if *ct.d.(**int64) == nil {
   278  				errf("want pointer to %v, got nil", *ct.wantptr)
   279  			} else if *ct.wantptr != intPtrValue(ct.d) {
   280  				errf("want pointer to %v, got %v", *ct.wantptr, intPtrValue(ct.d))
   281  			}
   282  		}
   283  		if ifptr, ok := ct.d.(*any); ok {
   284  			if !reflect.DeepEqual(ct.wantiface, scaniface) {
   285  				errf("want interface %#v, got %#v", ct.wantiface, scaniface)
   286  				continue
   287  			}
   288  			if srcBytes, ok := ct.s.([]byte); ok {
   289  				dstBytes := (*ifptr).([]byte)
   290  				if len(srcBytes) > 0 && &dstBytes[0] == &srcBytes[0] {
   291  					errf("copy into interface{} didn't copy []byte data")
   292  				}
   293  			}
   294  		}
   295  		if ct.wantusrdef != 0 && ct.wantusrdef != *ct.d.(*userDefined) {
   296  			errf("want userDefined %f, got %f", ct.wantusrdef, *ct.d.(*userDefined))
   297  		}
   298  		if len(ct.wantusrstr) != 0 && ct.wantusrstr != *ct.d.(*userDefinedString) {
   299  			errf("want userDefined %q, got %q", ct.wantusrstr, *ct.d.(*userDefinedString))
   300  		}
   301  	}
   302  }
   303  
   304  func TestNullString(t *testing.T) {
   305  	var ns NullString
   306  	convertAssign(&ns, []byte("foo"))
   307  	if !ns.Valid {
   308  		t.Errorf("expecting not null")
   309  	}
   310  	if ns.String != "foo" {
   311  		t.Errorf("expecting foo; got %q", ns.String)
   312  	}
   313  	convertAssign(&ns, nil)
   314  	if ns.Valid {
   315  		t.Errorf("expecting null on nil")
   316  	}
   317  	if ns.String != "" {
   318  		t.Errorf("expecting blank on nil; got %q", ns.String)
   319  	}
   320  }
   321  
   322  type valueConverterTest struct {
   323  	c       driver.ValueConverter
   324  	in, out any
   325  	err     string
   326  }
   327  
   328  var valueConverterTests = []valueConverterTest{
   329  	{driver.DefaultParameterConverter, NullString{"hi", true}, "hi", ""},
   330  	{driver.DefaultParameterConverter, NullString{"", false}, nil, ""},
   331  }
   332  
   333  func TestValueConverters(t *testing.T) {
   334  	for i, tt := range valueConverterTests {
   335  		out, err := tt.c.ConvertValue(tt.in)
   336  		goterr := ""
   337  		if err != nil {
   338  			goterr = err.Error()
   339  		}
   340  		if goterr != tt.err {
   341  			t.Errorf("test %d: %T(%T(%v)) error = %q; want error = %q",
   342  				i, tt.c, tt.in, tt.in, goterr, tt.err)
   343  		}
   344  		if tt.err != "" {
   345  			continue
   346  		}
   347  		if !reflect.DeepEqual(out, tt.out) {
   348  			t.Errorf("test %d: %T(%T(%v)) = %v (%T); want %v (%T)",
   349  				i, tt.c, tt.in, tt.in, out, out, tt.out, tt.out)
   350  		}
   351  	}
   352  }
   353  
   354  // Tests that assigning to RawBytes doesn't allocate (and also works).
   355  func TestRawBytesAllocs(t *testing.T) {
   356  	var tests = []struct {
   357  		name string
   358  		in   any
   359  		want string
   360  	}{
   361  		{"uint64", uint64(12345678), "12345678"},
   362  		{"uint32", uint32(1234), "1234"},
   363  		{"uint16", uint16(12), "12"},
   364  		{"uint8", uint8(1), "1"},
   365  		{"uint", uint(123), "123"},
   366  		{"int", int(123), "123"},
   367  		{"int8", int8(1), "1"},
   368  		{"int16", int16(12), "12"},
   369  		{"int32", int32(1234), "1234"},
   370  		{"int64", int64(12345678), "12345678"},
   371  		{"float32", float32(1.5), "1.5"},
   372  		{"float64", float64(64), "64"},
   373  		{"bool", false, "false"},
   374  		{"time", time.Unix(2, 5).UTC(), "1970-01-01T00:00:02.000000005Z"},
   375  	}
   376  	if asan.Enabled {
   377  		t.Skip("test allocates more with -asan; see #70079")
   378  	}
   379  
   380  	var buf RawBytes
   381  	rows := &Rows{}
   382  	test := func(name string, in any, want string) {
   383  		if err := convertAssignRows(&buf, in, rows); err != nil {
   384  			t.Fatalf("%s: convertAssign = %v", name, err)
   385  		}
   386  		match := len(buf) == len(want)
   387  		if match {
   388  			for i, b := range buf {
   389  				if want[i] != b {
   390  					match = false
   391  					break
   392  				}
   393  			}
   394  		}
   395  		if !match {
   396  			t.Fatalf("%s: got %q (len %d); want %q (len %d)", name, buf, len(buf), want, len(want))
   397  		}
   398  	}
   399  
   400  	n := testing.AllocsPerRun(100, func() {
   401  		for _, tt := range tests {
   402  			rows.raw = rows.raw[:0]
   403  			test(tt.name, tt.in, tt.want)
   404  		}
   405  	})
   406  
   407  	// The numbers below are only valid for 64-bit interface word sizes,
   408  	// and gc. With 32-bit words there are more convT2E allocs, and
   409  	// with gccgo, only pointers currently go in interface data.
   410  	// So only care on amd64 gc for now.
   411  	measureAllocs := false
   412  	switch runtime.GOARCH {
   413  	case "amd64", "arm64":
   414  		measureAllocs = runtime.Compiler == "gc"
   415  	}
   416  
   417  	if n > 0.5 && measureAllocs {
   418  		t.Fatalf("allocs = %v; want 0", n)
   419  	}
   420  
   421  	// This one involves a convT2E allocation, string -> interface{}
   422  	n = testing.AllocsPerRun(100, func() {
   423  		test("string", "foo", "foo")
   424  	})
   425  	if n > 1.5 && measureAllocs {
   426  		t.Fatalf("allocs = %v; want max 1", n)
   427  	}
   428  }
   429  
   430  // https://golang.org/issues/13905
   431  func TestUserDefinedBytes(t *testing.T) {
   432  	type userDefinedBytes []byte
   433  	var u userDefinedBytes
   434  	v := []byte("foo")
   435  
   436  	convertAssign(&u, v)
   437  	if &u[0] == &v[0] {
   438  		t.Fatal("userDefinedBytes got potentially dirty driver memory")
   439  	}
   440  }
   441  
   442  type Valuer_V string
   443  
   444  func (v Valuer_V) Value() (driver.Value, error) {
   445  	return strings.ToUpper(string(v)), nil
   446  }
   447  
   448  type Valuer_P string
   449  
   450  func (p *Valuer_P) Value() (driver.Value, error) {
   451  	if p == nil {
   452  		return "nil-to-str", nil
   453  	}
   454  	return strings.ToUpper(string(*p)), nil
   455  }
   456  
   457  func TestDriverArgs(t *testing.T) {
   458  	var nilValuerVPtr *Valuer_V
   459  	var nilValuerPPtr *Valuer_P
   460  	var nilStrPtr *string
   461  	tests := []struct {
   462  		args []any
   463  		want []driver.NamedValue
   464  	}{
   465  		0: {
   466  			args: []any{Valuer_V("foo")},
   467  			want: []driver.NamedValue{
   468  				{
   469  					Ordinal: 1,
   470  					Value:   "FOO",
   471  				},
   472  			},
   473  		},
   474  		1: {
   475  			args: []any{nilValuerVPtr},
   476  			want: []driver.NamedValue{
   477  				{
   478  					Ordinal: 1,
   479  					Value:   nil,
   480  				},
   481  			},
   482  		},
   483  		2: {
   484  			args: []any{nilValuerPPtr},
   485  			want: []driver.NamedValue{
   486  				{
   487  					Ordinal: 1,
   488  					Value:   "nil-to-str",
   489  				},
   490  			},
   491  		},
   492  		3: {
   493  			args: []any{"plain-str"},
   494  			want: []driver.NamedValue{
   495  				{
   496  					Ordinal: 1,
   497  					Value:   "plain-str",
   498  				},
   499  			},
   500  		},
   501  		4: {
   502  			args: []any{nilStrPtr},
   503  			want: []driver.NamedValue{
   504  				{
   505  					Ordinal: 1,
   506  					Value:   nil,
   507  				},
   508  			},
   509  		},
   510  	}
   511  	for i, tt := range tests {
   512  		ds := &driverStmt{Locker: &sync.Mutex{}, si: stubDriverStmt{nil}}
   513  		got, err := driverArgsConnLocked(nil, ds, tt.args)
   514  		if err != nil {
   515  			t.Errorf("test[%d]: %v", i, err)
   516  			continue
   517  		}
   518  		if !reflect.DeepEqual(got, tt.want) {
   519  			t.Errorf("test[%d]: got %v, want %v", i, got, tt.want)
   520  		}
   521  	}
   522  }
   523  
   524  type dec struct {
   525  	form        byte
   526  	neg         bool
   527  	coefficient [16]byte
   528  	exponent    int32
   529  }
   530  
   531  func (d dec) Decompose(buf []byte) (form byte, negative bool, coefficient []byte, exponent int32) {
   532  	coef := make([]byte, 16)
   533  	copy(coef, d.coefficient[:])
   534  	return d.form, d.neg, coef, d.exponent
   535  }
   536  
   537  func (d *dec) Compose(form byte, negative bool, coefficient []byte, exponent int32) error {
   538  	switch form {
   539  	default:
   540  		return fmt.Errorf("unknown form %d", form)
   541  	case 1, 2:
   542  		d.form = form
   543  		d.neg = negative
   544  		return nil
   545  	case 0:
   546  	}
   547  	d.form = form
   548  	d.neg = negative
   549  	d.exponent = exponent
   550  
   551  	// This isn't strictly correct, as the extra bytes could be all zero,
   552  	// ignore this for this test.
   553  	if len(coefficient) > 16 {
   554  		return fmt.Errorf("coefficient too large")
   555  	}
   556  	copy(d.coefficient[:], coefficient)
   557  
   558  	return nil
   559  }
   560  
   561  type decFinite struct {
   562  	neg         bool
   563  	coefficient [16]byte
   564  	exponent    int32
   565  }
   566  
   567  func (d decFinite) Decompose(buf []byte) (form byte, negative bool, coefficient []byte, exponent int32) {
   568  	coef := make([]byte, 16)
   569  	copy(coef, d.coefficient[:])
   570  	return 0, d.neg, coef, d.exponent
   571  }
   572  
   573  func (d *decFinite) Compose(form byte, negative bool, coefficient []byte, exponent int32) error {
   574  	switch form {
   575  	default:
   576  		return fmt.Errorf("unknown form %d", form)
   577  	case 1, 2:
   578  		return fmt.Errorf("unsupported form %d", form)
   579  	case 0:
   580  	}
   581  	d.neg = negative
   582  	d.exponent = exponent
   583  
   584  	// This isn't strictly correct, as the extra bytes could be all zero,
   585  	// ignore this for this test.
   586  	if len(coefficient) > 16 {
   587  		return fmt.Errorf("coefficient too large")
   588  	}
   589  	copy(d.coefficient[:], coefficient)
   590  
   591  	return nil
   592  }
   593  
   594  func TestDecimal(t *testing.T) {
   595  	list := []struct {
   596  		name string
   597  		in   decimalDecompose
   598  		out  dec
   599  		err  bool
   600  	}{
   601  		{name: "same", in: dec{exponent: -6}, out: dec{exponent: -6}},
   602  
   603  		// Ensure reflection is not used to assign the value by using different types.
   604  		{name: "diff", in: decFinite{exponent: -6}, out: dec{exponent: -6}},
   605  
   606  		{name: "bad-form", in: dec{form: 200}, err: true},
   607  	}
   608  	for _, item := range list {
   609  		t.Run(item.name, func(t *testing.T) {
   610  			out := dec{}
   611  			err := convertAssign(&out, item.in)
   612  			if item.err {
   613  				if err == nil {
   614  					t.Fatalf("unexpected nil error")
   615  				}
   616  				return
   617  			}
   618  			if err != nil {
   619  				t.Fatalf("unexpected error: %v", err)
   620  			}
   621  			if !reflect.DeepEqual(out, item.out) {
   622  				t.Fatalf("got %#v want %#v", out, item.out)
   623  			}
   624  		})
   625  	}
   626  }
   627  
   628  func TestConvertAssignNoContext(t *testing.T) {
   629  	const want = 42
   630  	var got int64
   631  	if err := ConvertAssign(driver.ScanContext{}, &got, want); err != nil {
   632  		t.Fatalf("ConvertAssign: %v", err)
   633  	}
   634  	if got != int64(want) {
   635  		t.Errorf("after ConvertAssign: got %v, want %v", got, want)
   636  	}
   637  }
   638  

View as plain text