github.com/cockroachdb/apd/v3@v3.2.0/sql_test.go (about) 1 // Copyright 2017 The Cockroach Authors. 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 12 // implied. See the License for the specific language governing 13 // permissions and limitations under the License. 14 15 //go:build sql 16 // +build sql 17 18 package apd 19 20 import ( 21 "database/sql" 22 "flag" 23 "testing" 24 25 _ "github.com/lib/pq" 26 ) 27 28 var ( 29 flagPostgres = flag.String("postgres", "postgres://postgres@localhost/apd?sslmode=disable", "Postgres connection string to an empty database") 30 ) 31 32 // TestSQL tests the Scan and Value methods of Decimal. 33 func TestSQL(t *testing.T) { 34 db, err := sql.Open("postgres", *flagPostgres) 35 if err != nil { 36 t.Fatal(err) 37 } 38 var a Decimal 39 if _, _, err = a.SetString("1234.567e5"); err != nil { 40 t.Fatal(err) 41 } 42 if _, err := db.Exec("drop table if exists d"); err != nil { 43 t.Fatal(err) 44 } 45 if _, err := db.Exec("create table d (v decimal)"); err != nil { 46 t.Fatal(err) 47 } 48 if _, err := db.Exec("insert into d values ($1)", a); err != nil { 49 t.Fatal(err) 50 } 51 if _, err := db.Exec("update d set v = v + 1e5"); err != nil { 52 t.Fatal(err) 53 } 54 var b, c, d Decimal 55 var nd NullDecimal 56 if err := db.QueryRow("select v, v::text, v::int, v::float, v from d").Scan(&a, &b, &c, &d, &nd); err != nil { 57 t.Fatal(err) 58 } 59 want, _, err := NewFromString("123556700") 60 if err != nil { 61 t.Fatal(err) 62 } 63 for i, v := range []*Decimal{&a, &b, &c, &d, &nd.Decimal} { 64 if v.Cmp(want) != 0 { 65 t.Fatalf("%d: unexpected: %s, want: %s", i, v.String(), want.String()) 66 } 67 } 68 69 if _, err := db.Exec("update d set v = NULL"); err != nil { 70 t.Fatal(err) 71 } 72 if err := db.QueryRow("select v from d").Scan(&nd); err != nil { 73 t.Fatal(err) 74 } 75 if nd.Valid { 76 t.Fatal("expected null") 77 } 78 79 var g Decimal 80 if err := db.QueryRow("select 0::decimal(19,9)").Scan(&g); err != nil { 81 t.Fatal(err) 82 } 83 zeroD, _, err := NewFromString("0.000000000") 84 if err != nil { 85 t.Fatal(err) 86 } 87 if g.String() != zeroD.String() { 88 t.Fatalf("expected 0::decimal(19.9) pg value %s match, found %s", g.String(), zeroD.String()) 89 } 90 }