You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1211 lines
30 KiB

  1. // Copyright 2015 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package bigquery
  15. import (
  16. "encoding/base64"
  17. "fmt"
  18. "math"
  19. "math/big"
  20. "testing"
  21. "time"
  22. "github.com/google/go-cmp/cmp"
  23. "cloud.google.com/go/civil"
  24. "cloud.google.com/go/internal/testutil"
  25. bq "google.golang.org/api/bigquery/v2"
  26. )
  27. func TestConvertBasicValues(t *testing.T) {
  28. schema := Schema{
  29. {Type: StringFieldType},
  30. {Type: IntegerFieldType},
  31. {Type: FloatFieldType},
  32. {Type: BooleanFieldType},
  33. {Type: BytesFieldType},
  34. {Type: NumericFieldType},
  35. }
  36. row := &bq.TableRow{
  37. F: []*bq.TableCell{
  38. {V: "a"},
  39. {V: "1"},
  40. {V: "1.2"},
  41. {V: "true"},
  42. {V: base64.StdEncoding.EncodeToString([]byte("foo"))},
  43. {V: "123.123456789"},
  44. },
  45. }
  46. got, err := convertRow(row, schema)
  47. if err != nil {
  48. t.Fatalf("error converting: %v", err)
  49. }
  50. want := []Value{"a", int64(1), 1.2, true, []byte("foo"), big.NewRat(123123456789, 1e9)}
  51. if !testutil.Equal(got, want) {
  52. t.Errorf("converting basic values: got:\n%v\nwant:\n%v", got, want)
  53. }
  54. }
  55. func TestConvertTime(t *testing.T) {
  56. schema := Schema{
  57. {Type: TimestampFieldType},
  58. {Type: DateFieldType},
  59. {Type: TimeFieldType},
  60. {Type: DateTimeFieldType},
  61. }
  62. ts := testTimestamp.Round(time.Millisecond)
  63. row := &bq.TableRow{
  64. F: []*bq.TableCell{
  65. {V: fmt.Sprintf("%.10f", float64(ts.UnixNano())/1e9)},
  66. {V: testDate.String()},
  67. {V: testTime.String()},
  68. {V: testDateTime.String()},
  69. },
  70. }
  71. got, err := convertRow(row, schema)
  72. if err != nil {
  73. t.Fatalf("error converting: %v", err)
  74. }
  75. want := []Value{ts, testDate, testTime, testDateTime}
  76. for i, g := range got {
  77. w := want[i]
  78. if !testutil.Equal(g, w) {
  79. t.Errorf("#%d: got:\n%v\nwant:\n%v", i, g, w)
  80. }
  81. }
  82. if got[0].(time.Time).Location() != time.UTC {
  83. t.Errorf("expected time zone UTC: got:\n%v", got)
  84. }
  85. }
  86. func TestConvertSmallTimes(t *testing.T) {
  87. for _, year := range []int{1600, 1066, 1} {
  88. want := time.Date(year, time.January, 1, 0, 0, 0, 0, time.UTC)
  89. s := fmt.Sprintf("%.10f", float64(want.Unix()))
  90. got, err := convertBasicType(s, TimestampFieldType)
  91. if err != nil {
  92. t.Fatal(err)
  93. }
  94. if !got.(time.Time).Equal(want) {
  95. t.Errorf("got %v, want %v", got, want)
  96. }
  97. }
  98. }
  99. func TestConvertNullValues(t *testing.T) {
  100. schema := Schema{{Type: StringFieldType}}
  101. row := &bq.TableRow{
  102. F: []*bq.TableCell{
  103. {V: nil},
  104. },
  105. }
  106. got, err := convertRow(row, schema)
  107. if err != nil {
  108. t.Fatalf("error converting: %v", err)
  109. }
  110. want := []Value{nil}
  111. if !testutil.Equal(got, want) {
  112. t.Errorf("converting null values: got:\n%v\nwant:\n%v", got, want)
  113. }
  114. }
  115. func TestBasicRepetition(t *testing.T) {
  116. schema := Schema{
  117. {Type: IntegerFieldType, Repeated: true},
  118. }
  119. row := &bq.TableRow{
  120. F: []*bq.TableCell{
  121. {
  122. V: []interface{}{
  123. map[string]interface{}{
  124. "v": "1",
  125. },
  126. map[string]interface{}{
  127. "v": "2",
  128. },
  129. map[string]interface{}{
  130. "v": "3",
  131. },
  132. },
  133. },
  134. },
  135. }
  136. got, err := convertRow(row, schema)
  137. if err != nil {
  138. t.Fatalf("error converting: %v", err)
  139. }
  140. want := []Value{[]Value{int64(1), int64(2), int64(3)}}
  141. if !testutil.Equal(got, want) {
  142. t.Errorf("converting basic repeated values: got:\n%v\nwant:\n%v", got, want)
  143. }
  144. }
  145. func TestNestedRecordContainingRepetition(t *testing.T) {
  146. schema := Schema{
  147. {
  148. Type: RecordFieldType,
  149. Schema: Schema{
  150. {Type: IntegerFieldType, Repeated: true},
  151. },
  152. },
  153. }
  154. row := &bq.TableRow{
  155. F: []*bq.TableCell{
  156. {
  157. V: map[string]interface{}{
  158. "f": []interface{}{
  159. map[string]interface{}{
  160. "v": []interface{}{
  161. map[string]interface{}{"v": "1"},
  162. map[string]interface{}{"v": "2"},
  163. map[string]interface{}{"v": "3"},
  164. },
  165. },
  166. },
  167. },
  168. },
  169. },
  170. }
  171. got, err := convertRow(row, schema)
  172. if err != nil {
  173. t.Fatalf("error converting: %v", err)
  174. }
  175. want := []Value{[]Value{[]Value{int64(1), int64(2), int64(3)}}}
  176. if !testutil.Equal(got, want) {
  177. t.Errorf("converting basic repeated values: got:\n%v\nwant:\n%v", got, want)
  178. }
  179. }
  180. func TestRepeatedRecordContainingRepetition(t *testing.T) {
  181. schema := Schema{
  182. {
  183. Type: RecordFieldType,
  184. Repeated: true,
  185. Schema: Schema{
  186. {Type: IntegerFieldType, Repeated: true},
  187. },
  188. },
  189. }
  190. row := &bq.TableRow{F: []*bq.TableCell{
  191. {
  192. V: []interface{}{ // repeated records.
  193. map[string]interface{}{ // first record.
  194. "v": map[string]interface{}{ // pointless single-key-map wrapper.
  195. "f": []interface{}{ // list of record fields.
  196. map[string]interface{}{ // only record (repeated ints)
  197. "v": []interface{}{ // pointless wrapper.
  198. map[string]interface{}{
  199. "v": "1",
  200. },
  201. map[string]interface{}{
  202. "v": "2",
  203. },
  204. map[string]interface{}{
  205. "v": "3",
  206. },
  207. },
  208. },
  209. },
  210. },
  211. },
  212. map[string]interface{}{ // second record.
  213. "v": map[string]interface{}{
  214. "f": []interface{}{
  215. map[string]interface{}{
  216. "v": []interface{}{
  217. map[string]interface{}{
  218. "v": "4",
  219. },
  220. map[string]interface{}{
  221. "v": "5",
  222. },
  223. map[string]interface{}{
  224. "v": "6",
  225. },
  226. },
  227. },
  228. },
  229. },
  230. },
  231. },
  232. },
  233. }}
  234. got, err := convertRow(row, schema)
  235. if err != nil {
  236. t.Fatalf("error converting: %v", err)
  237. }
  238. want := []Value{ // the row is a list of length 1, containing an entry for the repeated record.
  239. []Value{ // the repeated record is a list of length 2, containing an entry for each repetition.
  240. []Value{ // the record is a list of length 1, containing an entry for the repeated integer field.
  241. []Value{int64(1), int64(2), int64(3)}, // the repeated integer field is a list of length 3.
  242. },
  243. []Value{ // second record
  244. []Value{int64(4), int64(5), int64(6)},
  245. },
  246. },
  247. }
  248. if !testutil.Equal(got, want) {
  249. t.Errorf("converting repeated records with repeated values: got:\n%v\nwant:\n%v", got, want)
  250. }
  251. }
  252. func TestRepeatedRecordContainingRecord(t *testing.T) {
  253. schema := Schema{
  254. {
  255. Type: RecordFieldType,
  256. Repeated: true,
  257. Schema: Schema{
  258. {
  259. Type: StringFieldType,
  260. },
  261. {
  262. Type: RecordFieldType,
  263. Schema: Schema{
  264. {Type: IntegerFieldType},
  265. {Type: StringFieldType},
  266. },
  267. },
  268. },
  269. },
  270. }
  271. row := &bq.TableRow{F: []*bq.TableCell{
  272. {
  273. V: []interface{}{ // repeated records.
  274. map[string]interface{}{ // first record.
  275. "v": map[string]interface{}{ // pointless single-key-map wrapper.
  276. "f": []interface{}{ // list of record fields.
  277. map[string]interface{}{ // first record field (name)
  278. "v": "first repeated record",
  279. },
  280. map[string]interface{}{ // second record field (nested record).
  281. "v": map[string]interface{}{ // pointless single-key-map wrapper.
  282. "f": []interface{}{ // nested record fields
  283. map[string]interface{}{
  284. "v": "1",
  285. },
  286. map[string]interface{}{
  287. "v": "two",
  288. },
  289. },
  290. },
  291. },
  292. },
  293. },
  294. },
  295. map[string]interface{}{ // second record.
  296. "v": map[string]interface{}{
  297. "f": []interface{}{
  298. map[string]interface{}{
  299. "v": "second repeated record",
  300. },
  301. map[string]interface{}{
  302. "v": map[string]interface{}{
  303. "f": []interface{}{
  304. map[string]interface{}{
  305. "v": "3",
  306. },
  307. map[string]interface{}{
  308. "v": "four",
  309. },
  310. },
  311. },
  312. },
  313. },
  314. },
  315. },
  316. },
  317. },
  318. }}
  319. got, err := convertRow(row, schema)
  320. if err != nil {
  321. t.Fatalf("error converting: %v", err)
  322. }
  323. // TODO: test with flattenresults.
  324. want := []Value{ // the row is a list of length 1, containing an entry for the repeated record.
  325. []Value{ // the repeated record is a list of length 2, containing an entry for each repetition.
  326. []Value{ // record contains a string followed by a nested record.
  327. "first repeated record",
  328. []Value{
  329. int64(1),
  330. "two",
  331. },
  332. },
  333. []Value{ // second record.
  334. "second repeated record",
  335. []Value{
  336. int64(3),
  337. "four",
  338. },
  339. },
  340. },
  341. }
  342. if !testutil.Equal(got, want) {
  343. t.Errorf("converting repeated records containing record : got:\n%v\nwant:\n%v", got, want)
  344. }
  345. }
  346. func TestConvertRowErrors(t *testing.T) {
  347. // mismatched lengths
  348. if _, err := convertRow(&bq.TableRow{F: []*bq.TableCell{{V: ""}}}, Schema{}); err == nil {
  349. t.Error("got nil, want error")
  350. }
  351. v3 := map[string]interface{}{"v": 3}
  352. for _, test := range []struct {
  353. value interface{}
  354. fs FieldSchema
  355. }{
  356. {3, FieldSchema{Type: IntegerFieldType}}, // not a string
  357. {[]interface{}{v3}, // not a string, repeated
  358. FieldSchema{Type: IntegerFieldType, Repeated: true}},
  359. {map[string]interface{}{"f": []interface{}{v3}}, // not a string, nested
  360. FieldSchema{Type: RecordFieldType, Schema: Schema{{Type: IntegerFieldType}}}},
  361. {map[string]interface{}{"f": []interface{}{v3}}, // wrong length, nested
  362. FieldSchema{Type: RecordFieldType, Schema: Schema{}}},
  363. } {
  364. _, err := convertRow(
  365. &bq.TableRow{F: []*bq.TableCell{{V: test.value}}},
  366. Schema{&test.fs})
  367. if err == nil {
  368. t.Errorf("value %v, fs %v: got nil, want error", test.value, test.fs)
  369. }
  370. }
  371. // bad field type
  372. if _, err := convertBasicType("", FieldType("BAD")); err == nil {
  373. t.Error("got nil, want error")
  374. }
  375. }
  376. func TestValuesSaverConvertsToMap(t *testing.T) {
  377. testCases := []struct {
  378. vs ValuesSaver
  379. wantInsertID string
  380. wantRow map[string]Value
  381. }{
  382. {
  383. vs: ValuesSaver{
  384. Schema: Schema{
  385. {Name: "intField", Type: IntegerFieldType},
  386. {Name: "strField", Type: StringFieldType},
  387. {Name: "dtField", Type: DateTimeFieldType},
  388. {Name: "nField", Type: NumericFieldType},
  389. },
  390. InsertID: "iid",
  391. Row: []Value{1, "a",
  392. civil.DateTime{
  393. Date: civil.Date{Year: 1, Month: 2, Day: 3},
  394. Time: civil.Time{Hour: 4, Minute: 5, Second: 6, Nanosecond: 7000}},
  395. big.NewRat(123456789000, 1e9),
  396. },
  397. },
  398. wantInsertID: "iid",
  399. wantRow: map[string]Value{
  400. "intField": 1,
  401. "strField": "a",
  402. "dtField": "0001-02-03 04:05:06.000007",
  403. "nField": "123.456789000",
  404. },
  405. },
  406. {
  407. vs: ValuesSaver{
  408. Schema: Schema{
  409. {Name: "intField", Type: IntegerFieldType},
  410. {
  411. Name: "recordField",
  412. Type: RecordFieldType,
  413. Schema: Schema{
  414. {Name: "nestedInt", Type: IntegerFieldType, Repeated: true},
  415. },
  416. },
  417. },
  418. InsertID: "iid",
  419. Row: []Value{1, []Value{[]Value{2, 3}}},
  420. },
  421. wantInsertID: "iid",
  422. wantRow: map[string]Value{
  423. "intField": 1,
  424. "recordField": map[string]Value{
  425. "nestedInt": []Value{2, 3},
  426. },
  427. },
  428. },
  429. { // repeated nested field
  430. vs: ValuesSaver{
  431. Schema: Schema{
  432. {
  433. Name: "records",
  434. Type: RecordFieldType,
  435. Schema: Schema{
  436. {Name: "x", Type: IntegerFieldType},
  437. {Name: "y", Type: IntegerFieldType},
  438. },
  439. Repeated: true,
  440. },
  441. },
  442. InsertID: "iid",
  443. Row: []Value{ // a row is a []Value
  444. []Value{ // repeated field's value is a []Value
  445. []Value{1, 2}, // first record of the repeated field
  446. []Value{3, 4}, // second record
  447. },
  448. },
  449. },
  450. wantInsertID: "iid",
  451. wantRow: map[string]Value{
  452. "records": []Value{
  453. map[string]Value{"x": 1, "y": 2},
  454. map[string]Value{"x": 3, "y": 4},
  455. },
  456. },
  457. },
  458. }
  459. for _, tc := range testCases {
  460. gotRow, gotInsertID, err := tc.vs.Save()
  461. if err != nil {
  462. t.Errorf("Expected successful save; got: %v", err)
  463. continue
  464. }
  465. if !testutil.Equal(gotRow, tc.wantRow) {
  466. t.Errorf("%v row:\ngot:\n%+v\nwant:\n%+v", tc.vs, gotRow, tc.wantRow)
  467. }
  468. if !testutil.Equal(gotInsertID, tc.wantInsertID) {
  469. t.Errorf("%v ID:\ngot:\n%+v\nwant:\n%+v", tc.vs, gotInsertID, tc.wantInsertID)
  470. }
  471. }
  472. }
  473. func TestValuesToMapErrors(t *testing.T) {
  474. for _, test := range []struct {
  475. values []Value
  476. schema Schema
  477. }{
  478. { // mismatched length
  479. []Value{1},
  480. Schema{},
  481. },
  482. { // nested record not a slice
  483. []Value{1},
  484. Schema{{Type: RecordFieldType}},
  485. },
  486. { // nested record mismatched length
  487. []Value{[]Value{1}},
  488. Schema{{Type: RecordFieldType}},
  489. },
  490. { // nested repeated record not a slice
  491. []Value{[]Value{1}},
  492. Schema{{Type: RecordFieldType, Repeated: true}},
  493. },
  494. { // nested repeated record mismatched length
  495. []Value{[]Value{[]Value{1}}},
  496. Schema{{Type: RecordFieldType, Repeated: true}},
  497. },
  498. } {
  499. _, err := valuesToMap(test.values, test.schema)
  500. if err == nil {
  501. t.Errorf("%v, %v: got nil, want error", test.values, test.schema)
  502. }
  503. }
  504. }
  505. func TestStructSaver(t *testing.T) {
  506. schema := Schema{
  507. {Name: "s", Type: StringFieldType},
  508. {Name: "r", Type: IntegerFieldType, Repeated: true},
  509. {Name: "t", Type: TimeFieldType},
  510. {Name: "tr", Type: TimeFieldType, Repeated: true},
  511. {Name: "nested", Type: RecordFieldType, Schema: Schema{
  512. {Name: "b", Type: BooleanFieldType},
  513. }},
  514. {Name: "rnested", Type: RecordFieldType, Repeated: true, Schema: Schema{
  515. {Name: "b", Type: BooleanFieldType},
  516. }},
  517. {Name: "p", Type: IntegerFieldType, Required: false},
  518. {Name: "n", Type: NumericFieldType, Required: false},
  519. {Name: "nr", Type: NumericFieldType, Repeated: true},
  520. }
  521. type (
  522. N struct{ B bool }
  523. T struct {
  524. S string
  525. R []int
  526. T civil.Time
  527. TR []civil.Time
  528. Nested *N
  529. Rnested []*N
  530. P NullInt64
  531. N *big.Rat
  532. NR []*big.Rat
  533. }
  534. )
  535. check := func(msg string, in interface{}, want map[string]Value) {
  536. ss := StructSaver{
  537. Schema: schema,
  538. InsertID: "iid",
  539. Struct: in,
  540. }
  541. got, gotIID, err := ss.Save()
  542. if err != nil {
  543. t.Fatalf("%s: %v", msg, err)
  544. }
  545. if wantIID := "iid"; gotIID != wantIID {
  546. t.Errorf("%s: InsertID: got %q, want %q", msg, gotIID, wantIID)
  547. }
  548. if diff := testutil.Diff(got, want); diff != "" {
  549. t.Errorf("%s: %s", msg, diff)
  550. }
  551. }
  552. ct1 := civil.Time{Hour: 1, Minute: 2, Second: 3, Nanosecond: 4000}
  553. ct2 := civil.Time{Hour: 5, Minute: 6, Second: 7, Nanosecond: 8000}
  554. in := T{
  555. S: "x",
  556. R: []int{1, 2},
  557. T: ct1,
  558. TR: []civil.Time{ct1, ct2},
  559. Nested: &N{B: true},
  560. Rnested: []*N{{true}, {false}},
  561. P: NullInt64{Valid: true, Int64: 17},
  562. N: big.NewRat(123456, 1000),
  563. NR: []*big.Rat{big.NewRat(3, 1), big.NewRat(56789, 1e5)},
  564. }
  565. want := map[string]Value{
  566. "s": "x",
  567. "r": []int{1, 2},
  568. "t": "01:02:03.000004",
  569. "tr": []string{"01:02:03.000004", "05:06:07.000008"},
  570. "nested": map[string]Value{"b": true},
  571. "rnested": []Value{map[string]Value{"b": true}, map[string]Value{"b": false}},
  572. "p": NullInt64{Valid: true, Int64: 17},
  573. "n": "123.456000000",
  574. "nr": []string{"3.000000000", "0.567890000"},
  575. }
  576. check("all values", in, want)
  577. check("all values, ptr", &in, want)
  578. check("empty struct", T{}, map[string]Value{"s": "", "t": "00:00:00", "p": NullInt64{}})
  579. // Missing and extra fields ignored.
  580. type T2 struct {
  581. S string
  582. // missing R, Nested, RNested
  583. Extra int
  584. }
  585. check("missing and extra", T2{S: "x"}, map[string]Value{"s": "x"})
  586. check("nils in slice", T{Rnested: []*N{{true}, nil, {false}}},
  587. map[string]Value{
  588. "s": "",
  589. "t": "00:00:00",
  590. "p": NullInt64{},
  591. "rnested": []Value{map[string]Value{"b": true}, map[string]Value(nil), map[string]Value{"b": false}},
  592. })
  593. }
  594. func TestStructSaverErrors(t *testing.T) {
  595. type (
  596. badField struct {
  597. I int `bigquery:"@"`
  598. }
  599. badR struct{ R int }
  600. badRN struct{ R []int }
  601. )
  602. for i, test := range []struct {
  603. struct_ interface{}
  604. schema Schema
  605. }{
  606. {0, nil}, // not a struct
  607. {&badField{}, nil}, // bad field name
  608. {&badR{}, Schema{{Name: "r", Repeated: true}}}, // repeated field has bad type
  609. {&badR{}, Schema{{Name: "r", Type: RecordFieldType}}}, // nested field has bad type
  610. {&badRN{[]int{0}}, // nested repeated field has bad type
  611. Schema{{Name: "r", Type: RecordFieldType, Repeated: true}}},
  612. } {
  613. ss := &StructSaver{Struct: test.struct_, Schema: test.schema}
  614. _, _, err := ss.Save()
  615. if err == nil {
  616. t.Errorf("#%d, %v, %v: got nil, want error", i, test.struct_, test.schema)
  617. }
  618. }
  619. }
  620. func TestNumericString(t *testing.T) {
  621. for _, test := range []struct {
  622. in *big.Rat
  623. want string
  624. }{
  625. {big.NewRat(2, 3), "0.666666667"}, // round to 9 places
  626. {big.NewRat(1, 2), "0.500000000"},
  627. {big.NewRat(1, 2*1e8), "0.000000005"},
  628. {big.NewRat(5, 1e10), "0.000000001"}, // round up the 5 in the 10th decimal place
  629. {big.NewRat(-5, 1e10), "-0.000000001"}, // round half away from zero
  630. } {
  631. got := NumericString(test.in)
  632. if got != test.want {
  633. t.Errorf("%v: got %q, want %q", test.in, got, test.want)
  634. }
  635. }
  636. }
  637. func TestConvertRows(t *testing.T) {
  638. schema := Schema{
  639. {Type: StringFieldType},
  640. {Type: IntegerFieldType},
  641. {Type: FloatFieldType},
  642. {Type: BooleanFieldType},
  643. }
  644. rows := []*bq.TableRow{
  645. {F: []*bq.TableCell{
  646. {V: "a"},
  647. {V: "1"},
  648. {V: "1.2"},
  649. {V: "true"},
  650. }},
  651. {F: []*bq.TableCell{
  652. {V: "b"},
  653. {V: "2"},
  654. {V: "2.2"},
  655. {V: "false"},
  656. }},
  657. }
  658. want := [][]Value{
  659. {"a", int64(1), 1.2, true},
  660. {"b", int64(2), 2.2, false},
  661. }
  662. got, err := convertRows(rows, schema)
  663. if err != nil {
  664. t.Fatalf("got %v, want nil", err)
  665. }
  666. if !testutil.Equal(got, want) {
  667. t.Errorf("\ngot %v\nwant %v", got, want)
  668. }
  669. rows[0].F[0].V = 1
  670. _, err = convertRows(rows, schema)
  671. if err == nil {
  672. t.Error("got nil, want error")
  673. }
  674. }
  675. func TestValueList(t *testing.T) {
  676. schema := Schema{
  677. {Name: "s", Type: StringFieldType},
  678. {Name: "i", Type: IntegerFieldType},
  679. {Name: "f", Type: FloatFieldType},
  680. {Name: "b", Type: BooleanFieldType},
  681. }
  682. want := []Value{"x", 7, 3.14, true}
  683. var got []Value
  684. vl := (*valueList)(&got)
  685. if err := vl.Load(want, schema); err != nil {
  686. t.Fatal(err)
  687. }
  688. if !testutil.Equal(got, want) {
  689. t.Errorf("got %+v, want %+v", got, want)
  690. }
  691. // Load truncates, not appends.
  692. // https://github.com/GoogleCloudPlatform/google-cloud-go/issues/437
  693. if err := vl.Load(want, schema); err != nil {
  694. t.Fatal(err)
  695. }
  696. if !testutil.Equal(got, want) {
  697. t.Errorf("got %+v, want %+v", got, want)
  698. }
  699. }
  700. func TestValueMap(t *testing.T) {
  701. ns := Schema{
  702. {Name: "x", Type: IntegerFieldType},
  703. {Name: "y", Type: IntegerFieldType},
  704. }
  705. schema := Schema{
  706. {Name: "s", Type: StringFieldType},
  707. {Name: "i", Type: IntegerFieldType},
  708. {Name: "f", Type: FloatFieldType},
  709. {Name: "b", Type: BooleanFieldType},
  710. {Name: "n", Type: RecordFieldType, Schema: ns},
  711. {Name: "rn", Type: RecordFieldType, Schema: ns, Repeated: true},
  712. }
  713. in := []Value{"x", 7, 3.14, true,
  714. []Value{1, 2},
  715. []Value{[]Value{3, 4}, []Value{5, 6}},
  716. }
  717. var vm valueMap
  718. if err := vm.Load(in, schema); err != nil {
  719. t.Fatal(err)
  720. }
  721. want := map[string]Value{
  722. "s": "x",
  723. "i": 7,
  724. "f": 3.14,
  725. "b": true,
  726. "n": map[string]Value{"x": 1, "y": 2},
  727. "rn": []Value{
  728. map[string]Value{"x": 3, "y": 4},
  729. map[string]Value{"x": 5, "y": 6},
  730. },
  731. }
  732. if !testutil.Equal(vm, valueMap(want)) {
  733. t.Errorf("got\n%+v\nwant\n%+v", vm, want)
  734. }
  735. in = make([]Value, len(schema))
  736. want = map[string]Value{
  737. "s": nil,
  738. "i": nil,
  739. "f": nil,
  740. "b": nil,
  741. "n": nil,
  742. "rn": nil,
  743. }
  744. var vm2 valueMap
  745. if err := vm2.Load(in, schema); err != nil {
  746. t.Fatal(err)
  747. }
  748. if !testutil.Equal(vm2, valueMap(want)) {
  749. t.Errorf("got\n%+v\nwant\n%+v", vm2, want)
  750. }
  751. }
  752. var (
  753. // For testing StructLoader
  754. schema2 = Schema{
  755. {Name: "s", Type: StringFieldType},
  756. {Name: "s2", Type: StringFieldType},
  757. {Name: "by", Type: BytesFieldType},
  758. {Name: "I", Type: IntegerFieldType},
  759. {Name: "U", Type: IntegerFieldType},
  760. {Name: "F", Type: FloatFieldType},
  761. {Name: "B", Type: BooleanFieldType},
  762. {Name: "TS", Type: TimestampFieldType},
  763. {Name: "D", Type: DateFieldType},
  764. {Name: "T", Type: TimeFieldType},
  765. {Name: "DT", Type: DateTimeFieldType},
  766. {Name: "N", Type: NumericFieldType},
  767. {Name: "nested", Type: RecordFieldType, Schema: Schema{
  768. {Name: "nestS", Type: StringFieldType},
  769. {Name: "nestI", Type: IntegerFieldType},
  770. }},
  771. {Name: "t", Type: StringFieldType},
  772. }
  773. testTimestamp = time.Date(2016, 11, 5, 7, 50, 22, 8, time.UTC)
  774. testDate = civil.Date{Year: 2016, Month: 11, Day: 5}
  775. testTime = civil.Time{Hour: 7, Minute: 50, Second: 22, Nanosecond: 8}
  776. testDateTime = civil.DateTime{Date: testDate, Time: testTime}
  777. testNumeric = big.NewRat(123, 456)
  778. testValues = []Value{"x", "y", []byte{1, 2, 3}, int64(7), int64(8), 3.14, true,
  779. testTimestamp, testDate, testTime, testDateTime, testNumeric,
  780. []Value{"nested", int64(17)}, "z"}
  781. )
  782. type testStruct1 struct {
  783. B bool
  784. I int
  785. U uint16
  786. times
  787. S string
  788. S2 String
  789. By []byte
  790. s string
  791. F float64
  792. N *big.Rat
  793. Nested nested
  794. Tagged string `bigquery:"t"`
  795. }
  796. type String string
  797. type nested struct {
  798. NestS string
  799. NestI int
  800. }
  801. type times struct {
  802. TS time.Time
  803. T civil.Time
  804. D civil.Date
  805. DT civil.DateTime
  806. }
  807. func TestStructLoader(t *testing.T) {
  808. var ts1 testStruct1
  809. mustLoad(t, &ts1, schema2, testValues)
  810. // Note: the schema field named "s" gets matched to the exported struct
  811. // field "S", not the unexported "s".
  812. want := &testStruct1{
  813. B: true,
  814. I: 7,
  815. U: 8,
  816. F: 3.14,
  817. times: times{TS: testTimestamp, T: testTime, D: testDate, DT: testDateTime},
  818. S: "x",
  819. S2: "y",
  820. By: []byte{1, 2, 3},
  821. N: big.NewRat(123, 456),
  822. Nested: nested{NestS: "nested", NestI: 17},
  823. Tagged: "z",
  824. }
  825. if diff := testutil.Diff(&ts1, want, cmp.AllowUnexported(testStruct1{})); diff != "" {
  826. t.Error(diff)
  827. }
  828. // Test pointers to nested structs.
  829. type nestedPtr struct{ Nested *nested }
  830. var np nestedPtr
  831. mustLoad(t, &np, schema2, testValues)
  832. want2 := &nestedPtr{Nested: &nested{NestS: "nested", NestI: 17}}
  833. if diff := testutil.Diff(&np, want2); diff != "" {
  834. t.Error(diff)
  835. }
  836. // Existing values should be reused.
  837. nst := &nested{NestS: "x", NestI: -10}
  838. np = nestedPtr{Nested: nst}
  839. mustLoad(t, &np, schema2, testValues)
  840. if diff := testutil.Diff(&np, want2); diff != "" {
  841. t.Error(diff)
  842. }
  843. if np.Nested != nst {
  844. t.Error("nested struct pointers not equal")
  845. }
  846. }
  847. type repStruct struct {
  848. Nums []int
  849. ShortNums [2]int // to test truncation
  850. LongNums [5]int // to test padding with zeroes
  851. Nested []*nested
  852. }
  853. var (
  854. repSchema = Schema{
  855. {Name: "nums", Type: IntegerFieldType, Repeated: true},
  856. {Name: "shortNums", Type: IntegerFieldType, Repeated: true},
  857. {Name: "longNums", Type: IntegerFieldType, Repeated: true},
  858. {Name: "nested", Type: RecordFieldType, Repeated: true, Schema: Schema{
  859. {Name: "nestS", Type: StringFieldType},
  860. {Name: "nestI", Type: IntegerFieldType},
  861. }},
  862. }
  863. v123 = []Value{int64(1), int64(2), int64(3)}
  864. repValues = []Value{v123, v123, v123,
  865. []Value{
  866. []Value{"x", int64(1)},
  867. []Value{"y", int64(2)},
  868. },
  869. }
  870. )
  871. func TestStructLoaderRepeated(t *testing.T) {
  872. var r1 repStruct
  873. mustLoad(t, &r1, repSchema, repValues)
  874. want := repStruct{
  875. Nums: []int{1, 2, 3},
  876. ShortNums: [...]int{1, 2}, // extra values discarded
  877. LongNums: [...]int{1, 2, 3, 0, 0},
  878. Nested: []*nested{{"x", 1}, {"y", 2}},
  879. }
  880. if diff := testutil.Diff(r1, want); diff != "" {
  881. t.Error(diff)
  882. }
  883. r2 := repStruct{
  884. Nums: []int{-1, -2, -3, -4, -5}, // truncated to zero and appended to
  885. LongNums: [...]int{-1, -2, -3, -4, -5}, // unset elements are zeroed
  886. }
  887. mustLoad(t, &r2, repSchema, repValues)
  888. if diff := testutil.Diff(r2, want); diff != "" {
  889. t.Error(diff)
  890. }
  891. if got, want := cap(r2.Nums), 5; got != want {
  892. t.Errorf("cap(r2.Nums) = %d, want %d", got, want)
  893. }
  894. // Short slice case.
  895. r3 := repStruct{Nums: []int{-1}}
  896. mustLoad(t, &r3, repSchema, repValues)
  897. if diff := testutil.Diff(r3, want); diff != "" {
  898. t.Error(diff)
  899. }
  900. if got, want := cap(r3.Nums), 3; got != want {
  901. t.Errorf("cap(r3.Nums) = %d, want %d", got, want)
  902. }
  903. }
  904. type testStructNullable struct {
  905. String NullString
  906. Bytes []byte
  907. Integer NullInt64
  908. Float NullFloat64
  909. Boolean NullBool
  910. Timestamp NullTimestamp
  911. Date NullDate
  912. Time NullTime
  913. DateTime NullDateTime
  914. Numeric *big.Rat
  915. Record *subNullable
  916. }
  917. type subNullable struct {
  918. X NullInt64
  919. }
  920. var testStructNullableSchema = Schema{
  921. {Name: "String", Type: StringFieldType, Required: false},
  922. {Name: "Bytes", Type: BytesFieldType, Required: false},
  923. {Name: "Integer", Type: IntegerFieldType, Required: false},
  924. {Name: "Float", Type: FloatFieldType, Required: false},
  925. {Name: "Boolean", Type: BooleanFieldType, Required: false},
  926. {Name: "Timestamp", Type: TimestampFieldType, Required: false},
  927. {Name: "Date", Type: DateFieldType, Required: false},
  928. {Name: "Time", Type: TimeFieldType, Required: false},
  929. {Name: "DateTime", Type: DateTimeFieldType, Required: false},
  930. {Name: "Numeric", Type: NumericFieldType, Required: false},
  931. {Name: "Record", Type: RecordFieldType, Required: false, Schema: Schema{
  932. {Name: "X", Type: IntegerFieldType, Required: false},
  933. }},
  934. }
  935. func TestStructLoaderNullable(t *testing.T) {
  936. var ts testStructNullable
  937. nilVals := make([]Value, len(testStructNullableSchema))
  938. mustLoad(t, &ts, testStructNullableSchema, nilVals)
  939. want := testStructNullable{}
  940. if diff := testutil.Diff(ts, want); diff != "" {
  941. t.Error(diff)
  942. }
  943. nonnilVals := []Value{"x", []byte{1, 2, 3}, int64(1), 2.3, true, testTimestamp, testDate, testTime,
  944. testDateTime, big.NewRat(1, 2), []Value{int64(4)}}
  945. // All ts fields are nil. Loading non-nil values will cause them all to
  946. // be allocated.
  947. mustLoad(t, &ts, testStructNullableSchema, nonnilVals)
  948. want = testStructNullable{
  949. String: NullString{StringVal: "x", Valid: true},
  950. Bytes: []byte{1, 2, 3},
  951. Integer: NullInt64{Int64: 1, Valid: true},
  952. Float: NullFloat64{Float64: 2.3, Valid: true},
  953. Boolean: NullBool{Bool: true, Valid: true},
  954. Timestamp: NullTimestamp{Timestamp: testTimestamp, Valid: true},
  955. Date: NullDate{Date: testDate, Valid: true},
  956. Time: NullTime{Time: testTime, Valid: true},
  957. DateTime: NullDateTime{DateTime: testDateTime, Valid: true},
  958. Numeric: big.NewRat(1, 2),
  959. Record: &subNullable{X: NullInt64{Int64: 4, Valid: true}},
  960. }
  961. if diff := testutil.Diff(ts, want); diff != "" {
  962. t.Error(diff)
  963. }
  964. // Struct pointers are reused, byte slices are not.
  965. want = ts
  966. want.Bytes = []byte{17}
  967. vals2 := []Value{nil, []byte{17}, nil, nil, nil, nil, nil, nil, nil, nil, []Value{int64(7)}}
  968. mustLoad(t, &ts, testStructNullableSchema, vals2)
  969. if ts.Record != want.Record {
  970. t.Error("record pointers not identical")
  971. }
  972. }
  973. func TestStructLoaderOverflow(t *testing.T) {
  974. type S struct {
  975. I int16
  976. U uint16
  977. F float32
  978. }
  979. schema := Schema{
  980. {Name: "I", Type: IntegerFieldType},
  981. {Name: "U", Type: IntegerFieldType},
  982. {Name: "F", Type: FloatFieldType},
  983. }
  984. var s S
  985. z64 := int64(0)
  986. for _, vals := range [][]Value{
  987. {int64(math.MaxInt16 + 1), z64, 0},
  988. {z64, int64(math.MaxInt32), 0},
  989. {z64, int64(-1), 0},
  990. {z64, z64, math.MaxFloat32 * 2},
  991. } {
  992. if err := load(&s, schema, vals); err == nil {
  993. t.Errorf("%+v: got nil, want error", vals)
  994. }
  995. }
  996. }
  997. func TestStructLoaderFieldOverlap(t *testing.T) {
  998. // It's OK if the struct has fields that the schema does not, and vice versa.
  999. type S1 struct {
  1000. I int
  1001. X [][]int // not in the schema; does not even correspond to a valid BigQuery type
  1002. // many schema fields missing
  1003. }
  1004. var s1 S1
  1005. if err := load(&s1, schema2, testValues); err != nil {
  1006. t.Fatal(err)
  1007. }
  1008. want1 := S1{I: 7}
  1009. if diff := testutil.Diff(s1, want1); diff != "" {
  1010. t.Error(diff)
  1011. }
  1012. // It's even valid to have no overlapping fields at all.
  1013. type S2 struct{ Z int }
  1014. var s2 S2
  1015. mustLoad(t, &s2, schema2, testValues)
  1016. want2 := S2{}
  1017. if diff := testutil.Diff(s2, want2); diff != "" {
  1018. t.Error(diff)
  1019. }
  1020. }
  1021. func TestStructLoaderErrors(t *testing.T) {
  1022. check := func(sp interface{}) {
  1023. var sl structLoader
  1024. err := sl.set(sp, schema2)
  1025. if err == nil {
  1026. t.Errorf("%T: got nil, want error", sp)
  1027. }
  1028. }
  1029. type bad1 struct{ F int32 } // wrong type for FLOAT column
  1030. check(&bad1{})
  1031. type bad2 struct{ I uint } // unsupported integer type
  1032. check(&bad2{})
  1033. type bad3 struct {
  1034. I int `bigquery:"@"`
  1035. } // bad field name
  1036. check(&bad3{})
  1037. type bad4 struct{ Nested int } // non-struct for nested field
  1038. check(&bad4{})
  1039. type bad5 struct{ Nested struct{ NestS int } } // bad nested struct
  1040. check(&bad5{})
  1041. bad6 := &struct{ Nums int }{} // non-slice for repeated field
  1042. sl := structLoader{}
  1043. err := sl.set(bad6, repSchema)
  1044. if err == nil {
  1045. t.Errorf("%T: got nil, want error", bad6)
  1046. }
  1047. // sl.set's error is sticky, even with good input.
  1048. err2 := sl.set(&repStruct{}, repSchema)
  1049. if err2 != err {
  1050. t.Errorf("%v != %v, expected equal", err2, err)
  1051. }
  1052. // sl.Load is similarly sticky
  1053. err2 = sl.Load(nil, nil)
  1054. if err2 != err {
  1055. t.Errorf("%v != %v, expected equal", err2, err)
  1056. }
  1057. // Null values.
  1058. schema := Schema{
  1059. {Name: "i", Type: IntegerFieldType},
  1060. {Name: "f", Type: FloatFieldType},
  1061. {Name: "b", Type: BooleanFieldType},
  1062. {Name: "s", Type: StringFieldType},
  1063. {Name: "d", Type: DateFieldType},
  1064. {Name: "r", Type: RecordFieldType, Schema: Schema{{Name: "X", Type: IntegerFieldType}}},
  1065. }
  1066. type s struct {
  1067. I int
  1068. F float64
  1069. B bool
  1070. S string
  1071. D civil.Date
  1072. }
  1073. vals := []Value{int64(0), 0.0, false, "", testDate}
  1074. mustLoad(t, &s{}, schema, vals)
  1075. for i, e := range vals {
  1076. vals[i] = nil
  1077. got := load(&s{}, schema, vals)
  1078. if got != errNoNulls {
  1079. t.Errorf("#%d: got %v, want %v", i, got, errNoNulls)
  1080. }
  1081. vals[i] = e
  1082. }
  1083. // Using more than one struct type with the same structLoader.
  1084. type different struct {
  1085. B bool
  1086. I int
  1087. times
  1088. S string
  1089. s string
  1090. Nums []int
  1091. }
  1092. sl = structLoader{}
  1093. if err := sl.set(&testStruct1{}, schema2); err != nil {
  1094. t.Fatal(err)
  1095. }
  1096. err = sl.set(&different{}, schema2)
  1097. if err == nil {
  1098. t.Error("different struct types: got nil, want error")
  1099. }
  1100. }
  1101. func mustLoad(t *testing.T, pval interface{}, schema Schema, vals []Value) {
  1102. if err := load(pval, schema, vals); err != nil {
  1103. t.Fatalf("loading: %v", err)
  1104. }
  1105. }
  1106. func load(pval interface{}, schema Schema, vals []Value) error {
  1107. var sl structLoader
  1108. if err := sl.set(pval, schema); err != nil {
  1109. return err
  1110. }
  1111. return sl.Load(vals, nil)
  1112. }
  1113. func BenchmarkStructLoader_NoCompile(b *testing.B) {
  1114. benchmarkStructLoader(b, false)
  1115. }
  1116. func BenchmarkStructLoader_Compile(b *testing.B) {
  1117. benchmarkStructLoader(b, true)
  1118. }
  1119. func benchmarkStructLoader(b *testing.B, compile bool) {
  1120. var ts1 testStruct1
  1121. for i := 0; i < b.N; i++ {
  1122. var sl structLoader
  1123. for j := 0; j < 10; j++ {
  1124. if err := load(&ts1, schema2, testValues); err != nil {
  1125. b.Fatal(err)
  1126. }
  1127. if !compile {
  1128. sl.typ = nil
  1129. }
  1130. }
  1131. }
  1132. }