summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/lib/pq/oid/gen.go
blob: 7c634cdc5cd6385855fe09d6c910ead3f3934fc8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// +build ignore

// Generate the table of OID values
// Run with 'go run gen.go'.
package main

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"os/exec"
	"strings"

	_ "github.com/lib/pq"
)

// OID represent a postgres Object Identifier Type.
type OID struct {
	ID   int
	Type string
}

// Name returns an upper case version of the oid type.
func (o OID) Name() string {
	return strings.ToUpper(o.Type)
}

func main() {
	datname := os.Getenv("PGDATABASE")
	sslmode := os.Getenv("PGSSLMODE")

	if datname == "" {
		os.Setenv("PGDATABASE", "pqgotest")
	}

	if sslmode == "" {
		os.Setenv("PGSSLMODE", "disable")
	}

	db, err := sql.Open("postgres", "")
	if err != nil {
		log.Fatal(err)
	}
	rows, err := db.Query(`
		SELECT typname, oid
		FROM pg_type WHERE oid < 10000
		ORDER BY oid;
	`)
	if err != nil {
		log.Fatal(err)
	}
	oids := make([]*OID, 0)
	for rows.Next() {
		var oid OID
		if err = rows.Scan(&oid.Type, &oid.ID); err != nil {
			log.Fatal(err)
		}
		oids = append(oids, &oid)
	}
	if err = rows.Err(); err != nil {
		log.Fatal(err)
	}
	cmd := exec.Command("gofmt")
	cmd.Stderr = os.Stderr
	w, err := cmd.StdinPipe()
	if err != nil {
		log.Fatal(err)
	}
	f, err := os.Create("types.go")
	if err != nil {
		log.Fatal(err)
	}
	cmd.Stdout = f
	err = cmd.Start()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Fprintln(w, "// Code generated by gen.go. DO NOT EDIT.")
	fmt.Fprintln(w, "\npackage oid")
	fmt.Fprintln(w, "const (")
	for _, oid := range oids {
		fmt.Fprintf(w, "T_%s Oid = %d\n", oid.Type, oid.ID)
	}
	fmt.Fprintln(w, ")")
	fmt.Fprintln(w, "var TypeName = map[Oid]string{")
	for _, oid := range oids {
		fmt.Fprintf(w, "T_%s: \"%s\",\n", oid.Type, oid.Name())
	}
	fmt.Fprintln(w, "}")
	w.Close()
	cmd.Wait()
}