batch.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. package pgx
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "github.com/jackc/pgx/v5/pgconn"
  7. )
  8. // QueuedQuery is a query that has been queued for execution via a Batch.
  9. type QueuedQuery struct {
  10. SQL string
  11. Arguments []any
  12. Fn batchItemFunc
  13. sd *pgconn.StatementDescription
  14. }
  15. type batchItemFunc func(br BatchResults) error
  16. // Query sets fn to be called when the response to qq is received.
  17. func (qq *QueuedQuery) Query(fn func(rows Rows) error) {
  18. qq.Fn = func(br BatchResults) error {
  19. rows, _ := br.Query()
  20. defer rows.Close()
  21. err := fn(rows)
  22. if err != nil {
  23. return err
  24. }
  25. rows.Close()
  26. return rows.Err()
  27. }
  28. }
  29. // Query sets fn to be called when the response to qq is received.
  30. func (qq *QueuedQuery) QueryRow(fn func(row Row) error) {
  31. qq.Fn = func(br BatchResults) error {
  32. row := br.QueryRow()
  33. return fn(row)
  34. }
  35. }
  36. // Exec sets fn to be called when the response to qq is received.
  37. //
  38. // Note: for simple batch insert uses where it is not required to handle
  39. // each potential error individually, it's sufficient to not set any callbacks,
  40. // and just handle the return value of BatchResults.Close.
  41. func (qq *QueuedQuery) Exec(fn func(ct pgconn.CommandTag) error) {
  42. qq.Fn = func(br BatchResults) error {
  43. ct, err := br.Exec()
  44. if err != nil {
  45. return err
  46. }
  47. return fn(ct)
  48. }
  49. }
  50. // Batch queries are a way of bundling multiple queries together to avoid
  51. // unnecessary network round trips. A Batch must only be sent once.
  52. type Batch struct {
  53. QueuedQueries []*QueuedQuery
  54. }
  55. // Queue queues a query to batch b. query can be an SQL query or the name of a prepared statement. The only pgx option
  56. // argument that is supported is QueryRewriter. Queries are executed using the connection's DefaultQueryExecMode.
  57. //
  58. // While query can contain multiple statements if the connection's DefaultQueryExecMode is QueryModeSimple, this should
  59. // be avoided. QueuedQuery.Fn must not be set as it will only be called for the first query. That is, QueuedQuery.Query,
  60. // QueuedQuery.QueryRow, and QueuedQuery.Exec must not be called. In addition, any error messages or tracing that
  61. // include the current query may reference the wrong query.
  62. func (b *Batch) Queue(query string, arguments ...any) *QueuedQuery {
  63. qq := &QueuedQuery{
  64. SQL: query,
  65. Arguments: arguments,
  66. }
  67. b.QueuedQueries = append(b.QueuedQueries, qq)
  68. return qq
  69. }
  70. // Len returns number of queries that have been queued so far.
  71. func (b *Batch) Len() int {
  72. return len(b.QueuedQueries)
  73. }
  74. type BatchResults interface {
  75. // Exec reads the results from the next query in the batch as if the query has been sent with Conn.Exec. Prefer
  76. // calling Exec on the QueuedQuery, or just calling Close.
  77. Exec() (pgconn.CommandTag, error)
  78. // Query reads the results from the next query in the batch as if the query has been sent with Conn.Query. Prefer
  79. // calling Query on the QueuedQuery.
  80. Query() (Rows, error)
  81. // QueryRow reads the results from the next query in the batch as if the query has been sent with Conn.QueryRow.
  82. // Prefer calling QueryRow on the QueuedQuery.
  83. QueryRow() Row
  84. // Close closes the batch operation. All unread results are read and any callback functions registered with
  85. // QueuedQuery.Query, QueuedQuery.QueryRow, or QueuedQuery.Exec will be called. If a callback function returns an
  86. // error or the batch encounters an error subsequent callback functions will not be called.
  87. //
  88. // For simple batch inserts inside a transaction or similar queries, it's sufficient to not set any callbacks,
  89. // and just handle the return value of Close.
  90. //
  91. // Close must be called before the underlying connection can be used again. Any error that occurred during a batch
  92. // operation may have made it impossible to resyncronize the connection with the server. In this case the underlying
  93. // connection will have been closed.
  94. //
  95. // Close is safe to call multiple times. If it returns an error subsequent calls will return the same error. Callback
  96. // functions will not be rerun.
  97. Close() error
  98. }
  99. type batchResults struct {
  100. ctx context.Context
  101. conn *Conn
  102. mrr *pgconn.MultiResultReader
  103. err error
  104. b *Batch
  105. qqIdx int
  106. closed bool
  107. endTraced bool
  108. }
  109. // Exec reads the results from the next query in the batch as if the query has been sent with Exec.
  110. func (br *batchResults) Exec() (pgconn.CommandTag, error) {
  111. if br.err != nil {
  112. return pgconn.CommandTag{}, br.err
  113. }
  114. if br.closed {
  115. return pgconn.CommandTag{}, fmt.Errorf("batch already closed")
  116. }
  117. query, arguments, _ := br.nextQueryAndArgs()
  118. if !br.mrr.NextResult() {
  119. err := br.mrr.Close()
  120. if err == nil {
  121. err = errors.New("no more results in batch")
  122. }
  123. if br.conn.batchTracer != nil {
  124. br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
  125. SQL: query,
  126. Args: arguments,
  127. Err: err,
  128. })
  129. }
  130. return pgconn.CommandTag{}, err
  131. }
  132. commandTag, err := br.mrr.ResultReader().Close()
  133. if err != nil {
  134. br.err = err
  135. br.mrr.Close()
  136. }
  137. if br.conn.batchTracer != nil {
  138. br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
  139. SQL: query,
  140. Args: arguments,
  141. CommandTag: commandTag,
  142. Err: br.err,
  143. })
  144. }
  145. return commandTag, br.err
  146. }
  147. // Query reads the results from the next query in the batch as if the query has been sent with Query.
  148. func (br *batchResults) Query() (Rows, error) {
  149. query, arguments, ok := br.nextQueryAndArgs()
  150. if !ok {
  151. query = "batch query"
  152. }
  153. if br.err != nil {
  154. return &baseRows{err: br.err, closed: true}, br.err
  155. }
  156. if br.closed {
  157. alreadyClosedErr := fmt.Errorf("batch already closed")
  158. return &baseRows{err: alreadyClosedErr, closed: true}, alreadyClosedErr
  159. }
  160. rows := br.conn.getRows(br.ctx, query, arguments)
  161. rows.batchTracer = br.conn.batchTracer
  162. if !br.mrr.NextResult() {
  163. rows.err = br.mrr.Close()
  164. if rows.err == nil {
  165. rows.err = errors.New("no more results in batch")
  166. }
  167. rows.closed = true
  168. if br.conn.batchTracer != nil {
  169. br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
  170. SQL: query,
  171. Args: arguments,
  172. Err: rows.err,
  173. })
  174. }
  175. return rows, rows.err
  176. }
  177. rows.resultReader = br.mrr.ResultReader()
  178. return rows, nil
  179. }
  180. // QueryRow reads the results from the next query in the batch as if the query has been sent with QueryRow.
  181. func (br *batchResults) QueryRow() Row {
  182. rows, _ := br.Query()
  183. return (*connRow)(rows.(*baseRows))
  184. }
  185. // Close closes the batch operation. Any error that occurred during a batch operation may have made it impossible to
  186. // resyncronize the connection with the server. In this case the underlying connection will have been closed.
  187. func (br *batchResults) Close() error {
  188. defer func() {
  189. if !br.endTraced {
  190. if br.conn != nil && br.conn.batchTracer != nil {
  191. br.conn.batchTracer.TraceBatchEnd(br.ctx, br.conn, TraceBatchEndData{Err: br.err})
  192. }
  193. br.endTraced = true
  194. }
  195. invalidateCachesOnBatchResultsError(br.conn, br.b, br.err)
  196. }()
  197. if br.err != nil {
  198. return br.err
  199. }
  200. if br.closed {
  201. return nil
  202. }
  203. // Read and run fn for all remaining items
  204. for br.err == nil && !br.closed && br.b != nil && br.qqIdx < len(br.b.QueuedQueries) {
  205. if br.b.QueuedQueries[br.qqIdx].Fn != nil {
  206. err := br.b.QueuedQueries[br.qqIdx].Fn(br)
  207. if err != nil {
  208. br.err = err
  209. }
  210. } else {
  211. br.Exec()
  212. }
  213. }
  214. br.closed = true
  215. err := br.mrr.Close()
  216. if br.err == nil {
  217. br.err = err
  218. }
  219. return br.err
  220. }
  221. func (br *batchResults) earlyError() error {
  222. return br.err
  223. }
  224. func (br *batchResults) nextQueryAndArgs() (query string, args []any, ok bool) {
  225. if br.b != nil && br.qqIdx < len(br.b.QueuedQueries) {
  226. bi := br.b.QueuedQueries[br.qqIdx]
  227. query = bi.SQL
  228. args = bi.Arguments
  229. ok = true
  230. br.qqIdx++
  231. }
  232. return
  233. }
  234. type pipelineBatchResults struct {
  235. ctx context.Context
  236. conn *Conn
  237. pipeline *pgconn.Pipeline
  238. lastRows *baseRows
  239. err error
  240. b *Batch
  241. qqIdx int
  242. closed bool
  243. endTraced bool
  244. }
  245. // Exec reads the results from the next query in the batch as if the query has been sent with Exec.
  246. func (br *pipelineBatchResults) Exec() (pgconn.CommandTag, error) {
  247. if br.err != nil {
  248. return pgconn.CommandTag{}, br.err
  249. }
  250. if br.closed {
  251. return pgconn.CommandTag{}, fmt.Errorf("batch already closed")
  252. }
  253. if br.lastRows != nil && br.lastRows.err != nil {
  254. return pgconn.CommandTag{}, br.err
  255. }
  256. query, arguments, err := br.nextQueryAndArgs()
  257. if err != nil {
  258. return pgconn.CommandTag{}, err
  259. }
  260. results, err := br.pipeline.GetResults()
  261. if err != nil {
  262. br.err = err
  263. return pgconn.CommandTag{}, br.err
  264. }
  265. var commandTag pgconn.CommandTag
  266. switch results := results.(type) {
  267. case *pgconn.ResultReader:
  268. commandTag, br.err = results.Close()
  269. default:
  270. return pgconn.CommandTag{}, fmt.Errorf("unexpected pipeline result: %T", results)
  271. }
  272. if br.conn.batchTracer != nil {
  273. br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
  274. SQL: query,
  275. Args: arguments,
  276. CommandTag: commandTag,
  277. Err: br.err,
  278. })
  279. }
  280. return commandTag, br.err
  281. }
  282. // Query reads the results from the next query in the batch as if the query has been sent with Query.
  283. func (br *pipelineBatchResults) Query() (Rows, error) {
  284. if br.err != nil {
  285. return &baseRows{err: br.err, closed: true}, br.err
  286. }
  287. if br.closed {
  288. alreadyClosedErr := fmt.Errorf("batch already closed")
  289. return &baseRows{err: alreadyClosedErr, closed: true}, alreadyClosedErr
  290. }
  291. if br.lastRows != nil && br.lastRows.err != nil {
  292. br.err = br.lastRows.err
  293. return &baseRows{err: br.err, closed: true}, br.err
  294. }
  295. query, arguments, err := br.nextQueryAndArgs()
  296. if err != nil {
  297. return &baseRows{err: err, closed: true}, err
  298. }
  299. rows := br.conn.getRows(br.ctx, query, arguments)
  300. rows.batchTracer = br.conn.batchTracer
  301. br.lastRows = rows
  302. results, err := br.pipeline.GetResults()
  303. if err != nil {
  304. br.err = err
  305. rows.err = err
  306. rows.closed = true
  307. if br.conn.batchTracer != nil {
  308. br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
  309. SQL: query,
  310. Args: arguments,
  311. Err: err,
  312. })
  313. }
  314. } else {
  315. switch results := results.(type) {
  316. case *pgconn.ResultReader:
  317. rows.resultReader = results
  318. default:
  319. err = fmt.Errorf("unexpected pipeline result: %T", results)
  320. br.err = err
  321. rows.err = err
  322. rows.closed = true
  323. }
  324. }
  325. return rows, rows.err
  326. }
  327. // QueryRow reads the results from the next query in the batch as if the query has been sent with QueryRow.
  328. func (br *pipelineBatchResults) QueryRow() Row {
  329. rows, _ := br.Query()
  330. return (*connRow)(rows.(*baseRows))
  331. }
  332. // Close closes the batch operation. Any error that occurred during a batch operation may have made it impossible to
  333. // resyncronize the connection with the server. In this case the underlying connection will have been closed.
  334. func (br *pipelineBatchResults) Close() error {
  335. defer func() {
  336. if !br.endTraced {
  337. if br.conn.batchTracer != nil {
  338. br.conn.batchTracer.TraceBatchEnd(br.ctx, br.conn, TraceBatchEndData{Err: br.err})
  339. }
  340. br.endTraced = true
  341. }
  342. invalidateCachesOnBatchResultsError(br.conn, br.b, br.err)
  343. }()
  344. if br.err == nil && br.lastRows != nil && br.lastRows.err != nil {
  345. br.err = br.lastRows.err
  346. }
  347. if br.closed {
  348. return br.err
  349. }
  350. // Read and run fn for all remaining items
  351. for br.err == nil && !br.closed && br.b != nil && br.qqIdx < len(br.b.QueuedQueries) {
  352. if br.b.QueuedQueries[br.qqIdx].Fn != nil {
  353. err := br.b.QueuedQueries[br.qqIdx].Fn(br)
  354. if err != nil {
  355. br.err = err
  356. }
  357. } else {
  358. br.Exec()
  359. }
  360. }
  361. br.closed = true
  362. err := br.pipeline.Close()
  363. if br.err == nil {
  364. br.err = err
  365. }
  366. return br.err
  367. }
  368. func (br *pipelineBatchResults) earlyError() error {
  369. return br.err
  370. }
  371. func (br *pipelineBatchResults) nextQueryAndArgs() (query string, args []any, err error) {
  372. if br.b == nil {
  373. return "", nil, errors.New("no reference to batch")
  374. }
  375. if br.qqIdx >= len(br.b.QueuedQueries) {
  376. return "", nil, errors.New("no more results in batch")
  377. }
  378. bi := br.b.QueuedQueries[br.qqIdx]
  379. br.qqIdx++
  380. return bi.SQL, bi.Arguments, nil
  381. }
  382. type emptyBatchResults struct {
  383. conn *Conn
  384. closed bool
  385. }
  386. // Exec reads the results from the next query in the batch as if the query has been sent with Exec.
  387. func (br *emptyBatchResults) Exec() (pgconn.CommandTag, error) {
  388. if br.closed {
  389. return pgconn.CommandTag{}, fmt.Errorf("batch already closed")
  390. }
  391. return pgconn.CommandTag{}, errors.New("no more results in batch")
  392. }
  393. // Query reads the results from the next query in the batch as if the query has been sent with Query.
  394. func (br *emptyBatchResults) Query() (Rows, error) {
  395. if br.closed {
  396. alreadyClosedErr := fmt.Errorf("batch already closed")
  397. return &baseRows{err: alreadyClosedErr, closed: true}, alreadyClosedErr
  398. }
  399. rows := br.conn.getRows(context.Background(), "", nil)
  400. rows.err = errors.New("no more results in batch")
  401. rows.closed = true
  402. return rows, rows.err
  403. }
  404. // QueryRow reads the results from the next query in the batch as if the query has been sent with QueryRow.
  405. func (br *emptyBatchResults) QueryRow() Row {
  406. rows, _ := br.Query()
  407. return (*connRow)(rows.(*baseRows))
  408. }
  409. // Close closes the batch operation. Any error that occurred during a batch operation may have made it impossible to
  410. // resyncronize the connection with the server. In this case the underlying connection will have been closed.
  411. func (br *emptyBatchResults) Close() error {
  412. br.closed = true
  413. return nil
  414. }
  415. // invalidates statement and description caches on batch results error
  416. func invalidateCachesOnBatchResultsError(conn *Conn, b *Batch, err error) {
  417. if err != nil && conn != nil && b != nil {
  418. if sc := conn.statementCache; sc != nil {
  419. for _, bi := range b.QueuedQueries {
  420. sc.Invalidate(bi.SQL)
  421. }
  422. }
  423. if sc := conn.descriptionCache; sc != nil {
  424. for _, bi := range b.QueuedQueries {
  425. sc.Invalidate(bi.SQL)
  426. }
  427. }
  428. }
  429. }