doc.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. /*
  2. Package pq is a pure Go Postgres driver for the database/sql package.
  3. In most cases clients will use the database/sql package instead of
  4. using this package directly. For example:
  5. import (
  6. "database/sql"
  7. _ "github.com/lib/pq"
  8. )
  9. func main() {
  10. db, err := sql.Open("postgres", "user=pqgotest dbname=pqgotest sslmode=verify-full")
  11. if err != nil {
  12. log.Fatal(err)
  13. }
  14. age := 21
  15. rows, err := db.Query("SELECT name FROM users WHERE age = $1", age)
  16. }
  17. You can also connect to a database using a URL. For example:
  18. db, err := sql.Open("postgres", "postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full")
  19. Connection String Parameters
  20. Similarly to libpq, when establishing a connection using pq you are expected to
  21. supply a connection string containing zero or more parameters.
  22. A subset of the connection parameters supported by libpq are also supported by pq.
  23. Additionally, pq also lets you specify run-time parameters (such as search_path or work_mem)
  24. directly in the connection string. This is different from libpq, which does not allow
  25. run-time parameters in the connection string, instead requiring you to supply
  26. them in the options parameter.
  27. For compatibility with libpq, the following special connection parameters are
  28. supported:
  29. * dbname - The name of the database to connect to
  30. * user - The user to sign in as
  31. * password - The user's password
  32. * host - The host to connect to. Values that start with / are for unix domain sockets. (default is localhost)
  33. * port - The port to bind to. (default is 5432)
  34. * sslmode - Whether or not to use SSL (default is require, this is not the default for libpq)
  35. * fallback_application_name - An application_name to fall back to if one isn't provided.
  36. * connect_timeout - Maximum wait for connection, in seconds. Zero or not specified means wait indefinitely.
  37. * sslcert - Cert file location. The file must contain PEM encoded data.
  38. * sslkey - Key file location. The file must contain PEM encoded data.
  39. * sslrootcert - The location of the root certificate file. The file must contain PEM encoded data.
  40. Valid values for sslmode are:
  41. * disable - No SSL
  42. * require - Always SSL (skip verification)
  43. * verify-ca - Always SSL (verify that the certificate presented by the server was signed by a trusted CA)
  44. * verify-full - Always SSL (verify that the certification presented by the server was signed by a trusted CA and the server host name matches the one in the certificate)
  45. See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  46. for more information about connection string parameters.
  47. Use single quotes for values that contain whitespace:
  48. "user=pqgotest password='with spaces'"
  49. A backslash will escape the next character in values:
  50. "user=space\ man password='it\'s valid'
  51. Note that the connection parameter client_encoding (which sets the
  52. text encoding for the connection) may be set but must be "UTF8",
  53. matching with the same rules as Postgres. It is an error to provide
  54. any other value.
  55. In addition to the parameters listed above, any run-time parameter that can be
  56. set at backend start time can be set in the connection string. For more
  57. information, see
  58. http://www.postgresql.org/docs/current/static/runtime-config.html.
  59. Most environment variables as specified at http://www.postgresql.org/docs/current/static/libpq-envars.html
  60. supported by libpq are also supported by pq. If any of the environment
  61. variables not supported by pq are set, pq will panic during connection
  62. establishment. Environment variables have a lower precedence than explicitly
  63. provided connection parameters.
  64. The pgpass mechanism as described in http://www.postgresql.org/docs/current/static/libpq-pgpass.html
  65. is supported, but on Windows PGPASSFILE must be specified explicitly.
  66. Queries
  67. database/sql does not dictate any specific format for parameter
  68. markers in query strings, and pq uses the Postgres-native ordinal markers,
  69. as shown above. The same marker can be reused for the same parameter:
  70. rows, err := db.Query(`SELECT name FROM users WHERE favorite_fruit = $1
  71. OR age BETWEEN $2 AND $2 + 3`, "orange", 64)
  72. pq does not support the LastInsertId() method of the Result type in database/sql.
  73. To return the identifier of an INSERT (or UPDATE or DELETE), use the Postgres
  74. RETURNING clause with a standard Query or QueryRow call:
  75. var userid int
  76. err := db.QueryRow(`INSERT INTO users(name, favorite_fruit, age)
  77. VALUES('beatrice', 'starfruit', 93) RETURNING id`).Scan(&userid)
  78. For more details on RETURNING, see the Postgres documentation:
  79. http://www.postgresql.org/docs/current/static/sql-insert.html
  80. http://www.postgresql.org/docs/current/static/sql-update.html
  81. http://www.postgresql.org/docs/current/static/sql-delete.html
  82. For additional instructions on querying see the documentation for the database/sql package.
  83. Errors
  84. pq may return errors of type *pq.Error which can be interrogated for error details:
  85. if err, ok := err.(*pq.Error); ok {
  86. fmt.Println("pq error:", err.Code.Name())
  87. }
  88. See the pq.Error type for details.
  89. Bulk imports
  90. You can perform bulk imports by preparing a statement returned by pq.CopyIn (or
  91. pq.CopyInSchema) in an explicit transaction (sql.Tx). The returned statement
  92. handle can then be repeatedly "executed" to copy data into the target table.
  93. After all data has been processed you should call Exec() once with no arguments
  94. to flush all buffered data. Any call to Exec() might return an error which
  95. should be handled appropriately, but because of the internal buffering an error
  96. returned by Exec() might not be related to the data passed in the call that
  97. failed.
  98. CopyIn uses COPY FROM internally. It is not possible to COPY outside of an
  99. explicit transaction in pq.
  100. Usage example:
  101. txn, err := db.Begin()
  102. if err != nil {
  103. log.Fatal(err)
  104. }
  105. stmt, err := txn.Prepare(pq.CopyIn("users", "name", "age"))
  106. if err != nil {
  107. log.Fatal(err)
  108. }
  109. for _, user := range users {
  110. _, err = stmt.Exec(user.Name, int64(user.Age))
  111. if err != nil {
  112. log.Fatal(err)
  113. }
  114. }
  115. _, err = stmt.Exec()
  116. if err != nil {
  117. log.Fatal(err)
  118. }
  119. err = stmt.Close()
  120. if err != nil {
  121. log.Fatal(err)
  122. }
  123. err = txn.Commit()
  124. if err != nil {
  125. log.Fatal(err)
  126. }
  127. Notifications
  128. PostgreSQL supports a simple publish/subscribe model over database
  129. connections. See http://www.postgresql.org/docs/current/static/sql-notify.html
  130. for more information about the general mechanism.
  131. To start listening for notifications, you first have to open a new connection
  132. to the database by calling NewListener. This connection can not be used for
  133. anything other than LISTEN / NOTIFY. Calling Listen will open a "notification
  134. channel"; once a notification channel is open, a notification generated on that
  135. channel will effect a send on the Listener.Notify channel. A notification
  136. channel will remain open until Unlisten is called, though connection loss might
  137. result in some notifications being lost. To solve this problem, Listener sends
  138. a nil pointer over the Notify channel any time the connection is re-established
  139. following a connection loss. The application can get information about the
  140. state of the underlying connection by setting an event callback in the call to
  141. NewListener.
  142. A single Listener can safely be used from concurrent goroutines, which means
  143. that there is often no need to create more than one Listener in your
  144. application. However, a Listener is always connected to a single database, so
  145. you will need to create a new Listener instance for every database you want to
  146. receive notifications in.
  147. The channel name in both Listen and Unlisten is case sensitive, and can contain
  148. any characters legal in an identifier (see
  149. http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
  150. for more information). Note that the channel name will be truncated to 63
  151. bytes by the PostgreSQL server.
  152. You can find a complete, working example of Listener usage at
  153. http://godoc.org/github.com/lib/pq/listen_example.
  154. */
  155. package pq