example_cli_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package sql_test
  5. import (
  6. "context"
  7. "database/sql"
  8. "flag"
  9. "log"
  10. "os"
  11. "os/signal"
  12. "time"
  13. )
  14. var pool *sql.DB // Database connection pool.
  15. func Example_openDBCLI() {
  16. id := flag.Int64("id", 0, "person ID to find")
  17. dsn := flag.String("dsn", os.Getenv("DSN"), "connection data source name")
  18. flag.Parse()
  19. if len(*dsn) == 0 {
  20. log.Fatal("missing dsn flag")
  21. }
  22. if *id == 0 {
  23. log.Fatal("missing person ID")
  24. }
  25. var err error
  26. // Opening a driver typically will not attempt to connect to the database.
  27. pool, err = sql.Open("driver-name", *dsn)
  28. if err != nil {
  29. // This will not be a connection error, but a DSN parse error or
  30. // another initialization error.
  31. log.Fatal("unable to use data source name", err)
  32. }
  33. defer pool.Close()
  34. pool.SetConnMaxLifetime(0)
  35. pool.SetMaxIdleConns(3)
  36. pool.SetMaxOpenConns(3)
  37. ctx, stop := context.WithCancel(context.Background())
  38. defer stop()
  39. appSignal := make(chan os.Signal, 3)
  40. signal.Notify(appSignal, os.Interrupt)
  41. go func() {
  42. select {
  43. case <-appSignal:
  44. stop()
  45. }
  46. }()
  47. Ping(ctx)
  48. Query(ctx, *id)
  49. }
  50. // Ping the database to verify DSN provided by the user is valid and the
  51. // server accessible. If the ping fails exit the program with an error.
  52. func Ping(ctx context.Context) {
  53. ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
  54. defer cancel()
  55. if err := pool.PingContext(ctx); err != nil {
  56. log.Fatalf("unable to connect to database: %v", err)
  57. }
  58. }
  59. // Query the database for the information requested and prints the results.
  60. // If the query fails exit the program with an error.
  61. func Query(ctx context.Context, id int64) {
  62. ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
  63. defer cancel()
  64. var name string
  65. err := pool.QueryRowContext(ctx, "select p.name from people as p where p.id = :id;", sql.Named("id", id)).Scan(&name)
  66. if err != nil {
  67. log.Fatal("unable to execute search query", err)
  68. }
  69. log.Println("name=", name)
  70. }