tx.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. package pgx
  2. import (
  3. "context"
  4. "errors"
  5. "strconv"
  6. "strings"
  7. "github.com/jackc/pgx/v5/pgconn"
  8. )
  9. // TxIsoLevel is the transaction isolation level (serializable, repeatable read, read committed or read uncommitted)
  10. type TxIsoLevel string
  11. // Transaction isolation levels
  12. const (
  13. Serializable TxIsoLevel = "serializable"
  14. RepeatableRead TxIsoLevel = "repeatable read"
  15. ReadCommitted TxIsoLevel = "read committed"
  16. ReadUncommitted TxIsoLevel = "read uncommitted"
  17. )
  18. // TxAccessMode is the transaction access mode (read write or read only)
  19. type TxAccessMode string
  20. // Transaction access modes
  21. const (
  22. ReadWrite TxAccessMode = "read write"
  23. ReadOnly TxAccessMode = "read only"
  24. )
  25. // TxDeferrableMode is the transaction deferrable mode (deferrable or not deferrable)
  26. type TxDeferrableMode string
  27. // Transaction deferrable modes
  28. const (
  29. Deferrable TxDeferrableMode = "deferrable"
  30. NotDeferrable TxDeferrableMode = "not deferrable"
  31. )
  32. // TxOptions are transaction modes within a transaction block
  33. type TxOptions struct {
  34. IsoLevel TxIsoLevel
  35. AccessMode TxAccessMode
  36. DeferrableMode TxDeferrableMode
  37. // BeginQuery is the SQL query that will be executed to begin the transaction. This allows using non-standard syntax
  38. // such as BEGIN PRIORITY HIGH with CockroachDB. If set this will override the other settings.
  39. BeginQuery string
  40. // CommitQuery is the SQL query that will be executed to commit the transaction.
  41. CommitQuery string
  42. }
  43. var emptyTxOptions TxOptions
  44. func (txOptions TxOptions) beginSQL() string {
  45. if txOptions == emptyTxOptions {
  46. return "begin"
  47. }
  48. if txOptions.BeginQuery != "" {
  49. return txOptions.BeginQuery
  50. }
  51. var buf strings.Builder
  52. buf.Grow(64) // 64 - maximum length of string with available options
  53. buf.WriteString("begin")
  54. if txOptions.IsoLevel != "" {
  55. buf.WriteString(" isolation level ")
  56. buf.WriteString(string(txOptions.IsoLevel))
  57. }
  58. if txOptions.AccessMode != "" {
  59. buf.WriteByte(' ')
  60. buf.WriteString(string(txOptions.AccessMode))
  61. }
  62. if txOptions.DeferrableMode != "" {
  63. buf.WriteByte(' ')
  64. buf.WriteString(string(txOptions.DeferrableMode))
  65. }
  66. return buf.String()
  67. }
  68. var ErrTxClosed = errors.New("tx is closed")
  69. // ErrTxCommitRollback occurs when an error has occurred in a transaction and
  70. // Commit() is called. PostgreSQL accepts COMMIT on aborted transactions, but
  71. // it is treated as ROLLBACK.
  72. var ErrTxCommitRollback = errors.New("commit unexpectedly resulted in rollback")
  73. // Begin starts a transaction. Unlike database/sql, the context only affects the begin command. i.e. there is no
  74. // auto-rollback on context cancellation.
  75. func (c *Conn) Begin(ctx context.Context) (Tx, error) {
  76. return c.BeginTx(ctx, TxOptions{})
  77. }
  78. // BeginTx starts a transaction with txOptions determining the transaction mode. Unlike database/sql, the context only
  79. // affects the begin command. i.e. there is no auto-rollback on context cancellation.
  80. func (c *Conn) BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error) {
  81. _, err := c.Exec(ctx, txOptions.beginSQL())
  82. if err != nil {
  83. // begin should never fail unless there is an underlying connection issue or
  84. // a context timeout. In either case, the connection is possibly broken.
  85. c.die()
  86. return nil, err
  87. }
  88. return &dbTx{
  89. conn: c,
  90. commitQuery: txOptions.CommitQuery,
  91. }, nil
  92. }
  93. // Tx represents a database transaction.
  94. //
  95. // Tx is an interface instead of a struct to enable connection pools to be implemented without relying on internal pgx
  96. // state, to support pseudo-nested transactions with savepoints, and to allow tests to mock transactions. However,
  97. // adding a method to an interface is technically a breaking change. If new methods are added to Conn it may be
  98. // desirable to add them to Tx as well. Because of this the Tx interface is partially excluded from semantic version
  99. // requirements. Methods will not be removed or changed, but new methods may be added.
  100. type Tx interface {
  101. // Begin starts a pseudo nested transaction.
  102. Begin(ctx context.Context) (Tx, error)
  103. // Commit commits the transaction if this is a real transaction or releases the savepoint if this is a pseudo nested
  104. // transaction. Commit will return an error where errors.Is(ErrTxClosed) is true if the Tx is already closed, but is
  105. // otherwise safe to call multiple times. If the commit fails with a rollback status (e.g. the transaction was already
  106. // in a broken state) then an error where errors.Is(ErrTxCommitRollback) is true will be returned.
  107. Commit(ctx context.Context) error
  108. // Rollback rolls back the transaction if this is a real transaction or rolls back to the savepoint if this is a
  109. // pseudo nested transaction. Rollback will return an error where errors.Is(ErrTxClosed) is true if the Tx is already
  110. // closed, but is otherwise safe to call multiple times. Hence, a defer tx.Rollback() is safe even if tx.Commit() will
  111. // be called first in a non-error condition. Any other failure of a real transaction will result in the connection
  112. // being closed.
  113. Rollback(ctx context.Context) error
  114. CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error)
  115. SendBatch(ctx context.Context, b *Batch) BatchResults
  116. LargeObjects() LargeObjects
  117. Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error)
  118. Exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error)
  119. Query(ctx context.Context, sql string, args ...any) (Rows, error)
  120. QueryRow(ctx context.Context, sql string, args ...any) Row
  121. // Conn returns the underlying *Conn that on which this transaction is executing.
  122. Conn() *Conn
  123. }
  124. // dbTx represents a database transaction.
  125. //
  126. // All dbTx methods return ErrTxClosed if Commit or Rollback has already been
  127. // called on the dbTx.
  128. type dbTx struct {
  129. conn *Conn
  130. savepointNum int64
  131. closed bool
  132. commitQuery string
  133. }
  134. // Begin starts a pseudo nested transaction implemented with a savepoint.
  135. func (tx *dbTx) Begin(ctx context.Context) (Tx, error) {
  136. if tx.closed {
  137. return nil, ErrTxClosed
  138. }
  139. tx.savepointNum++
  140. _, err := tx.conn.Exec(ctx, "savepoint sp_"+strconv.FormatInt(tx.savepointNum, 10))
  141. if err != nil {
  142. return nil, err
  143. }
  144. return &dbSimulatedNestedTx{tx: tx, savepointNum: tx.savepointNum}, nil
  145. }
  146. // Commit commits the transaction.
  147. func (tx *dbTx) Commit(ctx context.Context) error {
  148. if tx.closed {
  149. return ErrTxClosed
  150. }
  151. commandSQL := "commit"
  152. if tx.commitQuery != "" {
  153. commandSQL = tx.commitQuery
  154. }
  155. commandTag, err := tx.conn.Exec(ctx, commandSQL)
  156. tx.closed = true
  157. if err != nil {
  158. if tx.conn.PgConn().TxStatus() != 'I' {
  159. _ = tx.conn.Close(ctx) // already have error to return
  160. }
  161. return err
  162. }
  163. if commandTag.String() == "ROLLBACK" {
  164. return ErrTxCommitRollback
  165. }
  166. return nil
  167. }
  168. // Rollback rolls back the transaction. Rollback will return ErrTxClosed if the
  169. // Tx is already closed, but is otherwise safe to call multiple times. Hence, a
  170. // defer tx.Rollback() is safe even if tx.Commit() will be called first in a
  171. // non-error condition.
  172. func (tx *dbTx) Rollback(ctx context.Context) error {
  173. if tx.closed {
  174. return ErrTxClosed
  175. }
  176. _, err := tx.conn.Exec(ctx, "rollback")
  177. tx.closed = true
  178. if err != nil {
  179. // A rollback failure leaves the connection in an undefined state
  180. tx.conn.die()
  181. return err
  182. }
  183. return nil
  184. }
  185. // Exec delegates to the underlying *Conn
  186. func (tx *dbTx) Exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error) {
  187. if tx.closed {
  188. return pgconn.CommandTag{}, ErrTxClosed
  189. }
  190. return tx.conn.Exec(ctx, sql, arguments...)
  191. }
  192. // Prepare delegates to the underlying *Conn
  193. func (tx *dbTx) Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error) {
  194. if tx.closed {
  195. return nil, ErrTxClosed
  196. }
  197. return tx.conn.Prepare(ctx, name, sql)
  198. }
  199. // Query delegates to the underlying *Conn
  200. func (tx *dbTx) Query(ctx context.Context, sql string, args ...any) (Rows, error) {
  201. if tx.closed {
  202. // Because checking for errors can be deferred to the *Rows, build one with the error
  203. err := ErrTxClosed
  204. return &baseRows{closed: true, err: err}, err
  205. }
  206. return tx.conn.Query(ctx, sql, args...)
  207. }
  208. // QueryRow delegates to the underlying *Conn
  209. func (tx *dbTx) QueryRow(ctx context.Context, sql string, args ...any) Row {
  210. rows, _ := tx.Query(ctx, sql, args...)
  211. return (*connRow)(rows.(*baseRows))
  212. }
  213. // CopyFrom delegates to the underlying *Conn
  214. func (tx *dbTx) CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error) {
  215. if tx.closed {
  216. return 0, ErrTxClosed
  217. }
  218. return tx.conn.CopyFrom(ctx, tableName, columnNames, rowSrc)
  219. }
  220. // SendBatch delegates to the underlying *Conn
  221. func (tx *dbTx) SendBatch(ctx context.Context, b *Batch) BatchResults {
  222. if tx.closed {
  223. return &batchResults{err: ErrTxClosed}
  224. }
  225. return tx.conn.SendBatch(ctx, b)
  226. }
  227. // LargeObjects returns a LargeObjects instance for the transaction.
  228. func (tx *dbTx) LargeObjects() LargeObjects {
  229. return LargeObjects{tx: tx}
  230. }
  231. func (tx *dbTx) Conn() *Conn {
  232. return tx.conn
  233. }
  234. // dbSimulatedNestedTx represents a simulated nested transaction implemented by a savepoint.
  235. type dbSimulatedNestedTx struct {
  236. tx Tx
  237. savepointNum int64
  238. closed bool
  239. }
  240. // Begin starts a pseudo nested transaction implemented with a savepoint.
  241. func (sp *dbSimulatedNestedTx) Begin(ctx context.Context) (Tx, error) {
  242. if sp.closed {
  243. return nil, ErrTxClosed
  244. }
  245. return sp.tx.Begin(ctx)
  246. }
  247. // Commit releases the savepoint essentially committing the pseudo nested transaction.
  248. func (sp *dbSimulatedNestedTx) Commit(ctx context.Context) error {
  249. if sp.closed {
  250. return ErrTxClosed
  251. }
  252. _, err := sp.Exec(ctx, "release savepoint sp_"+strconv.FormatInt(sp.savepointNum, 10))
  253. sp.closed = true
  254. return err
  255. }
  256. // Rollback rolls back to the savepoint essentially rolling back the pseudo nested transaction. Rollback will return
  257. // ErrTxClosed if the dbSavepoint is already closed, but is otherwise safe to call multiple times. Hence, a defer sp.Rollback()
  258. // is safe even if sp.Commit() will be called first in a non-error condition.
  259. func (sp *dbSimulatedNestedTx) Rollback(ctx context.Context) error {
  260. if sp.closed {
  261. return ErrTxClosed
  262. }
  263. _, err := sp.Exec(ctx, "rollback to savepoint sp_"+strconv.FormatInt(sp.savepointNum, 10))
  264. sp.closed = true
  265. return err
  266. }
  267. // Exec delegates to the underlying Tx
  268. func (sp *dbSimulatedNestedTx) Exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error) {
  269. if sp.closed {
  270. return pgconn.CommandTag{}, ErrTxClosed
  271. }
  272. return sp.tx.Exec(ctx, sql, arguments...)
  273. }
  274. // Prepare delegates to the underlying Tx
  275. func (sp *dbSimulatedNestedTx) Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error) {
  276. if sp.closed {
  277. return nil, ErrTxClosed
  278. }
  279. return sp.tx.Prepare(ctx, name, sql)
  280. }
  281. // Query delegates to the underlying Tx
  282. func (sp *dbSimulatedNestedTx) Query(ctx context.Context, sql string, args ...any) (Rows, error) {
  283. if sp.closed {
  284. // Because checking for errors can be deferred to the *Rows, build one with the error
  285. err := ErrTxClosed
  286. return &baseRows{closed: true, err: err}, err
  287. }
  288. return sp.tx.Query(ctx, sql, args...)
  289. }
  290. // QueryRow delegates to the underlying Tx
  291. func (sp *dbSimulatedNestedTx) QueryRow(ctx context.Context, sql string, args ...any) Row {
  292. rows, _ := sp.Query(ctx, sql, args...)
  293. return (*connRow)(rows.(*baseRows))
  294. }
  295. // CopyFrom delegates to the underlying *Conn
  296. func (sp *dbSimulatedNestedTx) CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error) {
  297. if sp.closed {
  298. return 0, ErrTxClosed
  299. }
  300. return sp.tx.CopyFrom(ctx, tableName, columnNames, rowSrc)
  301. }
  302. // SendBatch delegates to the underlying *Conn
  303. func (sp *dbSimulatedNestedTx) SendBatch(ctx context.Context, b *Batch) BatchResults {
  304. if sp.closed {
  305. return &batchResults{err: ErrTxClosed}
  306. }
  307. return sp.tx.SendBatch(ctx, b)
  308. }
  309. func (sp *dbSimulatedNestedTx) LargeObjects() LargeObjects {
  310. return LargeObjects{tx: sp}
  311. }
  312. func (sp *dbSimulatedNestedTx) Conn() *Conn {
  313. return sp.tx.Conn()
  314. }
  315. // BeginFunc calls Begin on db and then calls fn. If fn does not return an error then it calls Commit on db. If fn
  316. // returns an error it calls Rollback on db. The context will be used when executing the transaction control statements
  317. // (BEGIN, ROLLBACK, and COMMIT) but does not otherwise affect the execution of fn.
  318. func BeginFunc(
  319. ctx context.Context,
  320. db interface {
  321. Begin(ctx context.Context) (Tx, error)
  322. },
  323. fn func(Tx) error,
  324. ) (err error) {
  325. var tx Tx
  326. tx, err = db.Begin(ctx)
  327. if err != nil {
  328. return err
  329. }
  330. return beginFuncExec(ctx, tx, fn)
  331. }
  332. // BeginTxFunc calls BeginTx on db and then calls fn. If fn does not return an error then it calls Commit on db. If fn
  333. // returns an error it calls Rollback on db. The context will be used when executing the transaction control statements
  334. // (BEGIN, ROLLBACK, and COMMIT) but does not otherwise affect the execution of fn.
  335. func BeginTxFunc(
  336. ctx context.Context,
  337. db interface {
  338. BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error)
  339. },
  340. txOptions TxOptions,
  341. fn func(Tx) error,
  342. ) (err error) {
  343. var tx Tx
  344. tx, err = db.BeginTx(ctx, txOptions)
  345. if err != nil {
  346. return err
  347. }
  348. return beginFuncExec(ctx, tx, fn)
  349. }
  350. func beginFuncExec(ctx context.Context, tx Tx, fn func(Tx) error) (err error) {
  351. defer func() {
  352. rollbackErr := tx.Rollback(ctx)
  353. if rollbackErr != nil && !errors.Is(rollbackErr, ErrTxClosed) {
  354. err = rollbackErr
  355. }
  356. }()
  357. fErr := fn(tx)
  358. if fErr != nil {
  359. _ = tx.Rollback(ctx) // ignore rollback error as there is already an error to return
  360. return fErr
  361. }
  362. return tx.Commit(ctx)
  363. }