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// +build sql
16
17package apd
18
19import (
20	"database/sql"
21	"flag"
22	"testing"
23
24	_ "github.com/lib/pq"
25)
26
27var (
28	flagPostgres = flag.String("postgres", "postgres://postgres@localhost/apd?sslmode=disable", "Postgres connection string to an empty database")
29)
30
31// TestSQL tests the Scan and Value methods of Decimal.
32func TestSQL(t *testing.T) {
33	db, err := sql.Open("postgres", *flagPostgres)
34	if err != nil {
35		t.Fatal(err)
36	}
37	a, _, err := NewFromString("1234.567e5")
38	if err != nil {
39		t.Fatal(err)
40	}
41	if _, err := db.Exec("drop table if exists d"); err != nil {
42		t.Fatal(err)
43	}
44	if _, err := db.Exec("create table d (v decimal)"); err != nil {
45		t.Fatal(err)
46	}
47	if _, err := db.Exec("insert into d values ($1)", a); err != nil {
48		t.Fatal(err)
49	}
50	if _, err := db.Exec("update d set v = v + 1e5"); err != nil {
51		t.Fatal(err)
52	}
53	var b, c, d Decimal
54	var nd NullDecimal
55	if err := db.QueryRow("select v, v::text, v::int, v::float, v from d").Scan(a, &b, &c, &d, &nd); err != nil {
56		t.Fatal(err)
57	}
58	want, _, err := NewFromString("123556700")
59	if err != nil {
60		t.Fatal(err)
61	}
62	for i, v := range []*Decimal{a, &b, &c, &d, &nd.Decimal} {
63		if v.Cmp(want) != 0 {
64			t.Fatalf("%d: unexpected: %s, want: %s", i, v.String(), want.String())
65		}
66	}
67
68	if _, err := db.Exec("update d set v = NULL"); err != nil {
69		t.Fatal(err)
70	}
71	if err := db.QueryRow("select v from d").Scan(&nd); err != nil {
72		t.Fatal(err)
73	}
74	if nd.Valid {
75		t.Fatal("expected null")
76	}
77}
78