doc.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. _ "github.com/lib/pq"
  7. "database/sql"
  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. Queries
  65. database/sql does not dictate any specific format for parameter
  66. markers in query strings, and pq uses the Postgres-native ordinal markers,
  67. as shown above. The same marker can be reused for the same parameter:
  68. rows, err := db.Query(`SELECT name FROM users WHERE favorite_fruit = $1
  69. OR age BETWEEN $2 AND $2 + 3`, "orange", 64)
  70. pq does not support the LastInsertId() method of the Result type in database/sql.
  71. To return the identifier of an INSERT (or UPDATE or DELETE), use the Postgres
  72. RETURNING clause with a standard Query or QueryRow call:
  73. var userid int
  74. err := db.QueryRow(`INSERT INTO users(name, favorite_fruit, age)
  75. VALUES('beatrice', 'starfruit', 93) RETURNING id`).Scan(&userid)
  76. For more details on RETURNING, see the Postgres documentation:
  77. http://www.postgresql.org/docs/current/static/sql-insert.html
  78. http://www.postgresql.org/docs/current/static/sql-update.html
  79. http://www.postgresql.org/docs/current/static/sql-delete.html
  80. For additional instructions on querying see the documentation for the database/sql package.
  81. Errors
  82. pq may return errors of type *pq.Error which can be interrogated for error details:
  83. if err, ok := err.(*pq.Error); ok {
  84. fmt.Println("pq error:", err.Code.Name())
  85. }
  86. See the pq.Error type for details.
  87. Bulk imports
  88. You can perform bulk imports by preparing a statement returned by pq.CopyIn (or
  89. pq.CopyInSchema) in an explicit transaction (sql.Tx). The returned statement
  90. handle can then be repeatedly "executed" to copy data into the target table.
  91. After all data has been processed you should call Exec() once with no arguments
  92. to flush all buffered data. Any call to Exec() might return an error which
  93. should be handled appropriately, but because of the internal buffering an error
  94. returned by Exec() might not be related to the data passed in the call that
  95. failed.
  96. CopyIn uses COPY FROM internally. It is not possible to COPY outside of an
  97. explicit transaction in pq.
  98. Usage example:
  99. txn, err := db.Begin()
  100. if err != nil {
  101. log.Fatal(err)
  102. }
  103. stmt, err := txn.Prepare(pq.CopyIn("users", "name", "age"))
  104. if err != nil {
  105. log.Fatal(err)
  106. }
  107. for _, user := range users {
  108. _, err = stmt.Exec(user.Name, int64(user.Age))
  109. if err != nil {
  110. log.Fatal(err)
  111. }
  112. }
  113. _, err = stmt.Exec()
  114. if err != nil {
  115. log.Fatal(err)
  116. }
  117. err = stmt.Close()
  118. if err != nil {
  119. log.Fatal(err)
  120. }
  121. err = txn.Commit()
  122. if err != nil {
  123. log.Fatal(err)
  124. }
  125. Notifications
  126. PostgreSQL supports a simple publish/subscribe model over database
  127. connections. See http://www.postgresql.org/docs/current/static/sql-notify.html
  128. for more information about the general mechanism.
  129. To start listening for notifications, you first have to open a new connection
  130. to the database by calling NewListener. This connection can not be used for
  131. anything other than LISTEN / NOTIFY. Calling Listen will open a "notification
  132. channel"; once a notification channel is open, a notification generated on that
  133. channel will effect a send on the Listener.Notify channel. A notification
  134. channel will remain open until Unlisten is called, though connection loss might
  135. result in some notifications being lost. To solve this problem, Listener sends
  136. a nil pointer over the Notify channel any time the connection is re-established
  137. following a connection loss. The application can get information about the
  138. state of the underlying connection by setting an event callback in the call to
  139. NewListener.
  140. A single Listener can safely be used from concurrent goroutines, which means
  141. that there is often no need to create more than one Listener in your
  142. application. However, a Listener is always connected to a single database, so
  143. you will need to create a new Listener instance for every database you want to
  144. receive notifications in.
  145. The channel name in both Listen and Unlisten is case sensitive, and can contain
  146. any characters legal in an identifier (see
  147. http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
  148. for more information). Note that the channel name will be truncated to 63
  149. bytes by the PostgreSQL server.
  150. You can find a complete, working example of Listener usage at
  151. http://godoc.org/github.com/lib/pq/listen_example.
  152. */
  153. package pq