doc.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. Data Types
  84. Parameters pass through driver.DefaultParameterConverter before they are handled
  85. by this package. When the binary_parameters connection option is enabled,
  86. []byte values are sent directly to the backend as data in binary format.
  87. This package returns the following types for values from the PostgreSQL backend:
  88. - integer types smallint, integer, and bigint are returned as int64
  89. - floating-point types real and double precision are returned as float64
  90. - character types char, varchar, and text are returned as string
  91. - temporal types date, time, timetz, timestamp, and timestamptz are returned as time.Time
  92. - the boolean type is returned as bool
  93. - the bytea type is returned as []byte
  94. All other types are returned directly from the backend as []byte values in text format.
  95. Errors
  96. pq may return errors of type *pq.Error which can be interrogated for error details:
  97. if err, ok := err.(*pq.Error); ok {
  98. fmt.Println("pq error:", err.Code.Name())
  99. }
  100. See the pq.Error type for details.
  101. Bulk imports
  102. You can perform bulk imports by preparing a statement returned by pq.CopyIn (or
  103. pq.CopyInSchema) in an explicit transaction (sql.Tx). The returned statement
  104. handle can then be repeatedly "executed" to copy data into the target table.
  105. After all data has been processed you should call Exec() once with no arguments
  106. to flush all buffered data. Any call to Exec() might return an error which
  107. should be handled appropriately, but because of the internal buffering an error
  108. returned by Exec() might not be related to the data passed in the call that
  109. failed.
  110. CopyIn uses COPY FROM internally. It is not possible to COPY outside of an
  111. explicit transaction in pq.
  112. Usage example:
  113. txn, err := db.Begin()
  114. if err != nil {
  115. log.Fatal(err)
  116. }
  117. stmt, err := txn.Prepare(pq.CopyIn("users", "name", "age"))
  118. if err != nil {
  119. log.Fatal(err)
  120. }
  121. for _, user := range users {
  122. _, err = stmt.Exec(user.Name, int64(user.Age))
  123. if err != nil {
  124. log.Fatal(err)
  125. }
  126. }
  127. _, err = stmt.Exec()
  128. if err != nil {
  129. log.Fatal(err)
  130. }
  131. err = stmt.Close()
  132. if err != nil {
  133. log.Fatal(err)
  134. }
  135. err = txn.Commit()
  136. if err != nil {
  137. log.Fatal(err)
  138. }
  139. Notifications
  140. PostgreSQL supports a simple publish/subscribe model over database
  141. connections. See http://www.postgresql.org/docs/current/static/sql-notify.html
  142. for more information about the general mechanism.
  143. To start listening for notifications, you first have to open a new connection
  144. to the database by calling NewListener. This connection can not be used for
  145. anything other than LISTEN / NOTIFY. Calling Listen will open a "notification
  146. channel"; once a notification channel is open, a notification generated on that
  147. channel will effect a send on the Listener.Notify channel. A notification
  148. channel will remain open until Unlisten is called, though connection loss might
  149. result in some notifications being lost. To solve this problem, Listener sends
  150. a nil pointer over the Notify channel any time the connection is re-established
  151. following a connection loss. The application can get information about the
  152. state of the underlying connection by setting an event callback in the call to
  153. NewListener.
  154. A single Listener can safely be used from concurrent goroutines, which means
  155. that there is often no need to create more than one Listener in your
  156. application. However, a Listener is always connected to a single database, so
  157. you will need to create a new Listener instance for every database you want to
  158. receive notifications in.
  159. The channel name in both Listen and Unlisten is case sensitive, and can contain
  160. any characters legal in an identifier (see
  161. http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
  162. for more information). Note that the channel name will be truncated to 63
  163. bytes by the PostgreSQL server.
  164. You can find a complete, working example of Listener usage at
  165. http://godoc.org/github.com/lib/pq/listen_example.
  166. */
  167. package pq