gen.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // +build ignore
  2. // Generate the table of OID values
  3. // Run with 'go run gen.go'.
  4. package main
  5. import (
  6. "database/sql"
  7. "fmt"
  8. "log"
  9. "os"
  10. "os/exec"
  11. "strings"
  12. _ "github.com/lib/pq"
  13. )
  14. // OID represent a postgres Object Identifier Type.
  15. type OID struct {
  16. ID int
  17. Type string
  18. }
  19. // Name returns an upper case version of the oid type.
  20. func (o OID) Name() string {
  21. return strings.ToUpper(o.Type)
  22. }
  23. func main() {
  24. datname := os.Getenv("PGDATABASE")
  25. sslmode := os.Getenv("PGSSLMODE")
  26. if datname == "" {
  27. os.Setenv("PGDATABASE", "pqgotest")
  28. }
  29. if sslmode == "" {
  30. os.Setenv("PGSSLMODE", "disable")
  31. }
  32. db, err := sql.Open("postgres", "")
  33. if err != nil {
  34. log.Fatal(err)
  35. }
  36. rows, err := db.Query(`
  37. SELECT typname, oid
  38. FROM pg_type WHERE oid < 10000
  39. ORDER BY oid;
  40. `)
  41. if err != nil {
  42. log.Fatal(err)
  43. }
  44. oids := make([]*OID, 0)
  45. for rows.Next() {
  46. var oid OID
  47. if err = rows.Scan(&oid.Type, &oid.ID); err != nil {
  48. log.Fatal(err)
  49. }
  50. oids = append(oids, &oid)
  51. }
  52. if err = rows.Err(); err != nil {
  53. log.Fatal(err)
  54. }
  55. cmd := exec.Command("gofmt")
  56. cmd.Stderr = os.Stderr
  57. w, err := cmd.StdinPipe()
  58. if err != nil {
  59. log.Fatal(err)
  60. }
  61. f, err := os.Create("types.go")
  62. if err != nil {
  63. log.Fatal(err)
  64. }
  65. cmd.Stdout = f
  66. err = cmd.Start()
  67. if err != nil {
  68. log.Fatal(err)
  69. }
  70. fmt.Fprintln(w, "// Code generated by gen.go. DO NOT EDIT.")
  71. fmt.Fprintln(w, "\npackage oid")
  72. fmt.Fprintln(w, "const (")
  73. for _, oid := range oids {
  74. fmt.Fprintf(w, "T_%s Oid = %d\n", oid.Type, oid.ID)
  75. }
  76. fmt.Fprintln(w, ")")
  77. fmt.Fprintln(w, "var TypeName = map[Oid]string{")
  78. for _, oid := range oids {
  79. fmt.Fprintf(w, "T_%s: \"%s\",\n", oid.Type, oid.Name())
  80. }
  81. fmt.Fprintln(w, "}")
  82. w.Close()
  83. cmd.Wait()
  84. }