You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

doc.go 8.7KB

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