copy_from.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. package pgx
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. "github.com/jackc/pgx/v5/internal/pgio"
  8. "github.com/jackc/pgx/v5/pgconn"
  9. )
  10. // CopyFromRows returns a CopyFromSource interface over the provided rows slice
  11. // making it usable by *Conn.CopyFrom.
  12. func CopyFromRows(rows [][]any) CopyFromSource {
  13. return &copyFromRows{rows: rows, idx: -1}
  14. }
  15. type copyFromRows struct {
  16. rows [][]any
  17. idx int
  18. }
  19. func (ctr *copyFromRows) Next() bool {
  20. ctr.idx++
  21. return ctr.idx < len(ctr.rows)
  22. }
  23. func (ctr *copyFromRows) Values() ([]any, error) {
  24. return ctr.rows[ctr.idx], nil
  25. }
  26. func (ctr *copyFromRows) Err() error {
  27. return nil
  28. }
  29. // CopyFromSlice returns a CopyFromSource interface over a dynamic func
  30. // making it usable by *Conn.CopyFrom.
  31. func CopyFromSlice(length int, next func(int) ([]any, error)) CopyFromSource {
  32. return &copyFromSlice{next: next, idx: -1, len: length}
  33. }
  34. type copyFromSlice struct {
  35. next func(int) ([]any, error)
  36. idx int
  37. len int
  38. err error
  39. }
  40. func (cts *copyFromSlice) Next() bool {
  41. cts.idx++
  42. return cts.idx < cts.len
  43. }
  44. func (cts *copyFromSlice) Values() ([]any, error) {
  45. values, err := cts.next(cts.idx)
  46. if err != nil {
  47. cts.err = err
  48. }
  49. return values, err
  50. }
  51. func (cts *copyFromSlice) Err() error {
  52. return cts.err
  53. }
  54. // CopyFromFunc returns a CopyFromSource interface that relies on nxtf for values.
  55. // nxtf returns rows until it either signals an 'end of data' by returning row=nil and err=nil,
  56. // or it returns an error. If nxtf returns an error, the copy is aborted.
  57. func CopyFromFunc(nxtf func() (row []any, err error)) CopyFromSource {
  58. return &copyFromFunc{next: nxtf}
  59. }
  60. type copyFromFunc struct {
  61. next func() ([]any, error)
  62. valueRow []any
  63. err error
  64. }
  65. func (g *copyFromFunc) Next() bool {
  66. g.valueRow, g.err = g.next()
  67. // only return true if valueRow exists and no error
  68. return g.valueRow != nil && g.err == nil
  69. }
  70. func (g *copyFromFunc) Values() ([]any, error) {
  71. return g.valueRow, g.err
  72. }
  73. func (g *copyFromFunc) Err() error {
  74. return g.err
  75. }
  76. // CopyFromSource is the interface used by *Conn.CopyFrom as the source for copy data.
  77. type CopyFromSource interface {
  78. // Next returns true if there is another row and makes the next row data
  79. // available to Values(). When there are no more rows available or an error
  80. // has occurred it returns false.
  81. Next() bool
  82. // Values returns the values for the current row.
  83. Values() ([]any, error)
  84. // Err returns any error that has been encountered by the CopyFromSource. If
  85. // this is not nil *Conn.CopyFrom will abort the copy.
  86. Err() error
  87. }
  88. type copyFrom struct {
  89. conn *Conn
  90. tableName Identifier
  91. columnNames []string
  92. rowSrc CopyFromSource
  93. readerErrChan chan error
  94. mode QueryExecMode
  95. }
  96. func (ct *copyFrom) run(ctx context.Context) (int64, error) {
  97. if ct.conn.copyFromTracer != nil {
  98. ctx = ct.conn.copyFromTracer.TraceCopyFromStart(ctx, ct.conn, TraceCopyFromStartData{
  99. TableName: ct.tableName,
  100. ColumnNames: ct.columnNames,
  101. })
  102. }
  103. quotedTableName := ct.tableName.Sanitize()
  104. cbuf := &bytes.Buffer{}
  105. for i, cn := range ct.columnNames {
  106. if i != 0 {
  107. cbuf.WriteString(", ")
  108. }
  109. cbuf.WriteString(quoteIdentifier(cn))
  110. }
  111. quotedColumnNames := cbuf.String()
  112. var sd *pgconn.StatementDescription
  113. switch ct.mode {
  114. case QueryExecModeExec, QueryExecModeSimpleProtocol:
  115. // These modes don't support the binary format. Before the inclusion of the
  116. // QueryExecModes, Conn.Prepare was called on every COPY operation to get
  117. // the OIDs. These prepared statements were not cached.
  118. //
  119. // Since that's the same behavior provided by QueryExecModeDescribeExec,
  120. // we'll default to that mode.
  121. ct.mode = QueryExecModeDescribeExec
  122. fallthrough
  123. case QueryExecModeCacheStatement, QueryExecModeCacheDescribe, QueryExecModeDescribeExec:
  124. var err error
  125. sd, err = ct.conn.getStatementDescription(
  126. ctx,
  127. ct.mode,
  128. fmt.Sprintf("select %s from %s", quotedColumnNames, quotedTableName),
  129. )
  130. if err != nil {
  131. return 0, fmt.Errorf("statement description failed: %w", err)
  132. }
  133. default:
  134. return 0, fmt.Errorf("unknown QueryExecMode: %v", ct.mode)
  135. }
  136. r, w := io.Pipe()
  137. doneChan := make(chan struct{})
  138. go func() {
  139. defer close(doneChan)
  140. // Purposely NOT using defer w.Close(). See https://github.com/golang/go/issues/24283.
  141. buf := ct.conn.wbuf
  142. buf = append(buf, "PGCOPY\n\377\r\n\000"...)
  143. buf = pgio.AppendInt32(buf, 0)
  144. buf = pgio.AppendInt32(buf, 0)
  145. moreRows := true
  146. for moreRows {
  147. var err error
  148. moreRows, buf, err = ct.buildCopyBuf(buf, sd)
  149. if err != nil {
  150. w.CloseWithError(err)
  151. return
  152. }
  153. if ct.rowSrc.Err() != nil {
  154. w.CloseWithError(ct.rowSrc.Err())
  155. return
  156. }
  157. if len(buf) > 0 {
  158. _, err = w.Write(buf)
  159. if err != nil {
  160. w.Close()
  161. return
  162. }
  163. }
  164. buf = buf[:0]
  165. }
  166. w.Close()
  167. }()
  168. commandTag, err := ct.conn.pgConn.CopyFrom(ctx, r, fmt.Sprintf("copy %s ( %s ) from stdin binary;", quotedTableName, quotedColumnNames))
  169. r.Close()
  170. <-doneChan
  171. if ct.conn.copyFromTracer != nil {
  172. ct.conn.copyFromTracer.TraceCopyFromEnd(ctx, ct.conn, TraceCopyFromEndData{
  173. CommandTag: commandTag,
  174. Err: err,
  175. })
  176. }
  177. return commandTag.RowsAffected(), err
  178. }
  179. func (ct *copyFrom) buildCopyBuf(buf []byte, sd *pgconn.StatementDescription) (bool, []byte, error) {
  180. const sendBufSize = 65536 - 5 // The packet has a 5-byte header
  181. lastBufLen := 0
  182. largestRowLen := 0
  183. for ct.rowSrc.Next() {
  184. lastBufLen = len(buf)
  185. values, err := ct.rowSrc.Values()
  186. if err != nil {
  187. return false, nil, err
  188. }
  189. if len(values) != len(ct.columnNames) {
  190. return false, nil, fmt.Errorf("expected %d values, got %d values", len(ct.columnNames), len(values))
  191. }
  192. buf = pgio.AppendInt16(buf, int16(len(ct.columnNames)))
  193. for i, val := range values {
  194. buf, err = encodeCopyValue(ct.conn.typeMap, buf, sd.Fields[i].DataTypeOID, val)
  195. if err != nil {
  196. return false, nil, err
  197. }
  198. }
  199. rowLen := len(buf) - lastBufLen
  200. if rowLen > largestRowLen {
  201. largestRowLen = rowLen
  202. }
  203. // Try not to overflow size of the buffer PgConn.CopyFrom will be reading into. If that happens then the nature of
  204. // io.Pipe means that the next Read will be short. This can lead to pathological send sizes such as 65531, 13, 65531
  205. // 13, 65531, 13, 65531, 13.
  206. if len(buf) > sendBufSize-largestRowLen {
  207. return true, buf, nil
  208. }
  209. }
  210. return false, buf, nil
  211. }
  212. // CopyFrom uses the PostgreSQL copy protocol to perform bulk data insertion. It returns the number of rows copied and
  213. // an error.
  214. //
  215. // CopyFrom requires all values use the binary format. A pgtype.Type that supports the binary format must be registered
  216. // for the type of each column. Almost all types implemented by pgx support the binary format.
  217. //
  218. // Even though enum types appear to be strings they still must be registered to use with CopyFrom. This can be done with
  219. // Conn.LoadType and pgtype.Map.RegisterType.
  220. func (c *Conn) CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error) {
  221. ct := &copyFrom{
  222. conn: c,
  223. tableName: tableName,
  224. columnNames: columnNames,
  225. rowSrc: rowSrc,
  226. readerErrChan: make(chan error),
  227. mode: c.config.DefaultQueryExecMode,
  228. }
  229. return ct.run(ctx)
  230. }