pool.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. package pgxpool
  2. import (
  3. "context"
  4. "errors"
  5. "math/rand/v2"
  6. "runtime"
  7. "strconv"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. "github.com/jackc/pgx/v5"
  12. "github.com/jackc/pgx/v5/pgconn"
  13. "github.com/jackc/puddle/v2"
  14. )
  15. var (
  16. defaultMaxConns = int32(4)
  17. defaultMinConns = int32(0)
  18. defaultMinIdleConns = int32(0)
  19. defaultMaxConnLifetime = time.Hour
  20. defaultMaxConnIdleTime = time.Minute * 30
  21. defaultHealthCheckPeriod = time.Minute
  22. )
  23. type connResource struct {
  24. conn *pgx.Conn
  25. conns []Conn
  26. poolRows []poolRow
  27. poolRowss []poolRows
  28. maxAgeTime time.Time
  29. }
  30. func (cr *connResource) getConn(p *Pool, res *puddle.Resource[*connResource]) *Conn {
  31. if len(cr.conns) == 0 {
  32. cr.conns = make([]Conn, 128)
  33. }
  34. c := &cr.conns[len(cr.conns)-1]
  35. cr.conns = cr.conns[0 : len(cr.conns)-1]
  36. c.res = res
  37. c.p = p
  38. return c
  39. }
  40. func (cr *connResource) getPoolRow(c *Conn, r pgx.Row) *poolRow {
  41. if len(cr.poolRows) == 0 {
  42. cr.poolRows = make([]poolRow, 128)
  43. }
  44. pr := &cr.poolRows[len(cr.poolRows)-1]
  45. cr.poolRows = cr.poolRows[0 : len(cr.poolRows)-1]
  46. pr.c = c
  47. pr.r = r
  48. return pr
  49. }
  50. func (cr *connResource) getPoolRows(c *Conn, r pgx.Rows) *poolRows {
  51. if len(cr.poolRowss) == 0 {
  52. cr.poolRowss = make([]poolRows, 128)
  53. }
  54. pr := &cr.poolRowss[len(cr.poolRowss)-1]
  55. cr.poolRowss = cr.poolRowss[0 : len(cr.poolRowss)-1]
  56. pr.c = c
  57. pr.r = r
  58. return pr
  59. }
  60. // Pool allows for connection reuse.
  61. type Pool struct {
  62. // 64 bit fields accessed with atomics must be at beginning of struct to guarantee alignment for certain 32-bit
  63. // architectures. See BUGS section of https://pkg.go.dev/sync/atomic and https://github.com/jackc/pgx/issues/1288.
  64. newConnsCount int64
  65. lifetimeDestroyCount int64
  66. idleDestroyCount int64
  67. p *puddle.Pool[*connResource]
  68. config *Config
  69. beforeConnect func(context.Context, *pgx.ConnConfig) error
  70. afterConnect func(context.Context, *pgx.Conn) error
  71. prepareConn func(context.Context, *pgx.Conn) (bool, error)
  72. afterRelease func(*pgx.Conn) bool
  73. beforeClose func(*pgx.Conn)
  74. shouldPing func(context.Context, ShouldPingParams) bool
  75. minConns int32
  76. minIdleConns int32
  77. maxConns int32
  78. maxConnLifetime time.Duration
  79. maxConnLifetimeJitter time.Duration
  80. maxConnIdleTime time.Duration
  81. healthCheckPeriod time.Duration
  82. pingTimeout time.Duration
  83. healthCheckMu sync.Mutex
  84. healthCheckTimer *time.Timer
  85. healthCheckChan chan struct{}
  86. acquireTracer AcquireTracer
  87. releaseTracer ReleaseTracer
  88. closeOnce sync.Once
  89. closeChan chan struct{}
  90. }
  91. // ShouldPingParams are the parameters passed to ShouldPing.
  92. type ShouldPingParams struct {
  93. Conn *pgx.Conn
  94. IdleDuration time.Duration
  95. }
  96. // Config is the configuration struct for creating a pool. It must be created by [ParseConfig] and then it can be
  97. // modified.
  98. type Config struct {
  99. ConnConfig *pgx.ConnConfig
  100. // BeforeConnect is called before a new connection is made. It is passed a copy of the underlying pgx.ConnConfig and
  101. // will not impact any existing open connections.
  102. BeforeConnect func(context.Context, *pgx.ConnConfig) error
  103. // AfterConnect is called after a connection is established, but before it is added to the pool.
  104. AfterConnect func(context.Context, *pgx.Conn) error
  105. // BeforeAcquire is called before a connection is acquired from the pool. It must return true to allow the
  106. // acquisition or false to indicate that the connection should be destroyed and a different connection should be
  107. // acquired.
  108. //
  109. // Deprecated: Use PrepareConn instead. If both PrepareConn and BeforeAcquire are set, PrepareConn will take
  110. // precedence, ignoring BeforeAcquire.
  111. BeforeAcquire func(context.Context, *pgx.Conn) bool
  112. // PrepareConn is called before a connection is acquired from the pool. If this function returns true, the connection
  113. // is considered valid, otherwise the connection is destroyed. If the function returns a non-nil error, the instigating
  114. // query will fail with the returned error.
  115. //
  116. // Specifically, this means that:
  117. //
  118. // - If it returns true and a nil error, the query proceeds as normal.
  119. // - If it returns true and an error, the connection will be returned to the pool, and the instigating query will fail with the returned error.
  120. // - If it returns false, and an error, the connection will be destroyed, and the query will fail with the returned error.
  121. // - If it returns false and a nil error, the connection will be destroyed, and the instigating query will be retried on a new connection.
  122. PrepareConn func(context.Context, *pgx.Conn) (bool, error)
  123. // AfterRelease is called after a connection is released, but before it is returned to the pool. It must return true to
  124. // return the connection to the pool or false to destroy the connection.
  125. AfterRelease func(*pgx.Conn) bool
  126. // BeforeClose is called right before a connection is closed and removed from the pool.
  127. BeforeClose func(*pgx.Conn)
  128. // ShouldPing is called after a connection is acquired from the pool. If it returns true, the connection is pinged to check for liveness.
  129. // If this func is not set, the default behavior is to ping connections that have been idle for at least 1 second.
  130. ShouldPing func(context.Context, ShouldPingParams) bool
  131. // MaxConnLifetime is the duration since creation after which a connection will be automatically closed.
  132. MaxConnLifetime time.Duration
  133. // MaxConnLifetimeJitter is the duration after MaxConnLifetime to randomly decide to close a connection.
  134. // This helps prevent all connections from being closed at the exact same time, starving the pool.
  135. MaxConnLifetimeJitter time.Duration
  136. // MaxConnIdleTime is the duration after which an idle connection will be automatically closed by the health check.
  137. MaxConnIdleTime time.Duration
  138. // PingTimeout is the maximum amount of time to wait for a connection to pong before considering it as unhealthy and
  139. // destroying it. If zero, the default is no timeout.
  140. PingTimeout time.Duration
  141. // MaxConns is the maximum size of the pool. The default is the greater of 4 or runtime.NumCPU().
  142. MaxConns int32
  143. // MinConns is the minimum size of the pool. After connection closes, the pool might dip below MinConns. A low
  144. // number of MinConns might mean the pool is empty after MaxConnLifetime until the health check has a chance
  145. // to create new connections.
  146. MinConns int32
  147. // MinIdleConns is the minimum number of idle connections in the pool. You can increase this to ensure that
  148. // there are always idle connections available. This can help reduce tail latencies during request processing,
  149. // as you can avoid the latency of establishing a new connection while handling requests. It is superior
  150. // to MinConns for this purpose.
  151. // Similar to MinConns, the pool might temporarily dip below MinIdleConns after connection closes.
  152. MinIdleConns int32
  153. // HealthCheckPeriod is the duration between checks of the health of idle connections.
  154. HealthCheckPeriod time.Duration
  155. createdByParseConfig bool // Used to enforce created by ParseConfig rule.
  156. }
  157. // Copy returns a deep copy of the config that is safe to use and modify.
  158. // The only exception is the tls.Config:
  159. // according to the tls.Config docs it must not be modified after creation.
  160. func (c *Config) Copy() *Config {
  161. newConfig := new(Config)
  162. *newConfig = *c
  163. newConfig.ConnConfig = c.ConnConfig.Copy()
  164. return newConfig
  165. }
  166. // ConnString returns the connection string as parsed by pgxpool.ParseConfig into pgxpool.Config.
  167. func (c *Config) ConnString() string { return c.ConnConfig.ConnString() }
  168. // New creates a new Pool. See [ParseConfig] for information on connString format.
  169. func New(ctx context.Context, connString string) (*Pool, error) {
  170. config, err := ParseConfig(connString)
  171. if err != nil {
  172. return nil, err
  173. }
  174. return NewWithConfig(ctx, config)
  175. }
  176. // NewWithConfig creates a new Pool. config must have been created by [ParseConfig].
  177. func NewWithConfig(ctx context.Context, config *Config) (*Pool, error) {
  178. // Default values are set in ParseConfig. Enforce initial creation by ParseConfig rather than setting defaults from
  179. // zero values.
  180. if !config.createdByParseConfig {
  181. panic("config must be created by ParseConfig")
  182. }
  183. prepareConn := config.PrepareConn
  184. if prepareConn == nil && config.BeforeAcquire != nil {
  185. prepareConn = func(ctx context.Context, conn *pgx.Conn) (bool, error) {
  186. return config.BeforeAcquire(ctx, conn), nil
  187. }
  188. }
  189. p := &Pool{
  190. config: config,
  191. beforeConnect: config.BeforeConnect,
  192. afterConnect: config.AfterConnect,
  193. prepareConn: prepareConn,
  194. afterRelease: config.AfterRelease,
  195. beforeClose: config.BeforeClose,
  196. minConns: config.MinConns,
  197. minIdleConns: config.MinIdleConns,
  198. maxConns: config.MaxConns,
  199. maxConnLifetime: config.MaxConnLifetime,
  200. maxConnLifetimeJitter: config.MaxConnLifetimeJitter,
  201. maxConnIdleTime: config.MaxConnIdleTime,
  202. pingTimeout: config.PingTimeout,
  203. healthCheckPeriod: config.HealthCheckPeriod,
  204. healthCheckChan: make(chan struct{}, 1),
  205. closeChan: make(chan struct{}),
  206. }
  207. if t, ok := config.ConnConfig.Tracer.(AcquireTracer); ok {
  208. p.acquireTracer = t
  209. }
  210. if t, ok := config.ConnConfig.Tracer.(ReleaseTracer); ok {
  211. p.releaseTracer = t
  212. }
  213. if config.ShouldPing != nil {
  214. p.shouldPing = config.ShouldPing
  215. } else {
  216. p.shouldPing = func(ctx context.Context, params ShouldPingParams) bool {
  217. return params.IdleDuration > time.Second
  218. }
  219. }
  220. var err error
  221. p.p, err = puddle.NewPool(
  222. &puddle.Config[*connResource]{
  223. Constructor: func(ctx context.Context) (*connResource, error) {
  224. atomic.AddInt64(&p.newConnsCount, 1)
  225. connConfig := p.config.ConnConfig.Copy()
  226. // Connection will continue in background even if Acquire is canceled. Ensure that a connect won't hang forever.
  227. if connConfig.ConnectTimeout <= 0 {
  228. connConfig.ConnectTimeout = 2 * time.Minute
  229. }
  230. if p.beforeConnect != nil {
  231. if err := p.beforeConnect(ctx, connConfig); err != nil {
  232. return nil, err
  233. }
  234. }
  235. conn, err := pgx.ConnectConfig(ctx, connConfig)
  236. if err != nil {
  237. return nil, err
  238. }
  239. if p.afterConnect != nil {
  240. err = p.afterConnect(ctx, conn)
  241. if err != nil {
  242. conn.Close(ctx)
  243. return nil, err
  244. }
  245. }
  246. jitterSecs := rand.Float64() * config.MaxConnLifetimeJitter.Seconds()
  247. maxAgeTime := time.Now().Add(config.MaxConnLifetime).Add(time.Duration(jitterSecs) * time.Second)
  248. cr := &connResource{
  249. conn: conn,
  250. conns: make([]Conn, 64),
  251. poolRows: make([]poolRow, 64),
  252. poolRowss: make([]poolRows, 64),
  253. maxAgeTime: maxAgeTime,
  254. }
  255. return cr, nil
  256. },
  257. Destructor: func(value *connResource) {
  258. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  259. conn := value.conn
  260. if p.beforeClose != nil {
  261. p.beforeClose(conn)
  262. }
  263. conn.Close(ctx)
  264. select {
  265. case <-conn.PgConn().CleanupDone():
  266. case <-ctx.Done():
  267. }
  268. cancel()
  269. },
  270. MaxSize: config.MaxConns,
  271. },
  272. )
  273. if err != nil {
  274. return nil, err
  275. }
  276. go func() {
  277. targetIdleResources := max(int(p.minConns), int(p.minIdleConns))
  278. p.createIdleResources(ctx, targetIdleResources)
  279. p.backgroundHealthCheck()
  280. }()
  281. return p, nil
  282. }
  283. // ParseConfig builds a Config from connString. It parses connString with the same behavior as [pgx.ParseConfig] with the
  284. // addition of the following variables:
  285. //
  286. // - pool_max_conns: integer greater than 0 (default 4)
  287. // - pool_min_conns: integer 0 or greater (default 0)
  288. // - pool_max_conn_lifetime: duration string (default 1 hour)
  289. // - pool_max_conn_idle_time: duration string (default 30 minutes)
  290. // - pool_health_check_period: duration string (default 1 minute)
  291. // - pool_max_conn_lifetime_jitter: duration string (default 0)
  292. //
  293. // See Config for definitions of these arguments.
  294. //
  295. // # Example Keyword/Value
  296. // user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca pool_max_conns=10 pool_max_conn_lifetime=1h30m
  297. //
  298. // # Example URL
  299. // postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca&pool_max_conns=10&pool_max_conn_lifetime=1h30m
  300. func ParseConfig(connString string) (*Config, error) {
  301. connConfig, err := pgx.ParseConfig(connString)
  302. if err != nil {
  303. return nil, err
  304. }
  305. config := &Config{
  306. ConnConfig: connConfig,
  307. createdByParseConfig: true,
  308. }
  309. if s, ok := config.ConnConfig.Config.RuntimeParams["pool_max_conns"]; ok {
  310. delete(connConfig.Config.RuntimeParams, "pool_max_conns")
  311. n, err := strconv.ParseInt(s, 10, 32)
  312. if err != nil {
  313. return nil, pgconn.NewParseConfigError(connString, "cannot parse pool_max_conns", err)
  314. }
  315. if n < 1 {
  316. return nil, pgconn.NewParseConfigError(connString, "pool_max_conns too small", err)
  317. }
  318. config.MaxConns = int32(n)
  319. } else {
  320. config.MaxConns = defaultMaxConns
  321. if numCPU := int32(runtime.NumCPU()); numCPU > config.MaxConns {
  322. config.MaxConns = numCPU
  323. }
  324. }
  325. if s, ok := config.ConnConfig.Config.RuntimeParams["pool_min_conns"]; ok {
  326. delete(connConfig.Config.RuntimeParams, "pool_min_conns")
  327. n, err := strconv.ParseInt(s, 10, 32)
  328. if err != nil {
  329. return nil, pgconn.NewParseConfigError(connString, "cannot parse pool_min_conns", err)
  330. }
  331. config.MinConns = int32(n)
  332. } else {
  333. config.MinConns = defaultMinConns
  334. }
  335. if s, ok := config.ConnConfig.Config.RuntimeParams["pool_min_idle_conns"]; ok {
  336. delete(connConfig.Config.RuntimeParams, "pool_min_idle_conns")
  337. n, err := strconv.ParseInt(s, 10, 32)
  338. if err != nil {
  339. return nil, pgconn.NewParseConfigError(connString, "cannot parse pool_min_idle_conns", err)
  340. }
  341. config.MinIdleConns = int32(n)
  342. } else {
  343. config.MinIdleConns = defaultMinIdleConns
  344. }
  345. if s, ok := config.ConnConfig.Config.RuntimeParams["pool_max_conn_lifetime"]; ok {
  346. delete(connConfig.Config.RuntimeParams, "pool_max_conn_lifetime")
  347. d, err := time.ParseDuration(s)
  348. if err != nil {
  349. return nil, pgconn.NewParseConfigError(connString, "cannot parse pool_max_conn_lifetime", err)
  350. }
  351. config.MaxConnLifetime = d
  352. } else {
  353. config.MaxConnLifetime = defaultMaxConnLifetime
  354. }
  355. if s, ok := config.ConnConfig.Config.RuntimeParams["pool_max_conn_idle_time"]; ok {
  356. delete(connConfig.Config.RuntimeParams, "pool_max_conn_idle_time")
  357. d, err := time.ParseDuration(s)
  358. if err != nil {
  359. return nil, pgconn.NewParseConfigError(connString, "cannot parse pool_max_conn_idle_time", err)
  360. }
  361. config.MaxConnIdleTime = d
  362. } else {
  363. config.MaxConnIdleTime = defaultMaxConnIdleTime
  364. }
  365. if s, ok := config.ConnConfig.Config.RuntimeParams["pool_health_check_period"]; ok {
  366. delete(connConfig.Config.RuntimeParams, "pool_health_check_period")
  367. d, err := time.ParseDuration(s)
  368. if err != nil {
  369. return nil, pgconn.NewParseConfigError(connString, "cannot parse pool_health_check_period", err)
  370. }
  371. config.HealthCheckPeriod = d
  372. } else {
  373. config.HealthCheckPeriod = defaultHealthCheckPeriod
  374. }
  375. if s, ok := config.ConnConfig.Config.RuntimeParams["pool_max_conn_lifetime_jitter"]; ok {
  376. delete(connConfig.Config.RuntimeParams, "pool_max_conn_lifetime_jitter")
  377. d, err := time.ParseDuration(s)
  378. if err != nil {
  379. return nil, pgconn.NewParseConfigError(connString, "cannot parse pool_max_conn_lifetime_jitter", err)
  380. }
  381. config.MaxConnLifetimeJitter = d
  382. }
  383. return config, nil
  384. }
  385. // Close closes all connections in the pool and rejects future Acquire calls. Blocks until all connections are returned
  386. // to pool and closed.
  387. func (p *Pool) Close() {
  388. p.closeOnce.Do(func() {
  389. close(p.closeChan)
  390. p.p.Close()
  391. })
  392. }
  393. func (p *Pool) isExpired(res *puddle.Resource[*connResource]) bool {
  394. return time.Now().After(res.Value().maxAgeTime)
  395. }
  396. func (p *Pool) triggerHealthCheck() {
  397. const healthCheckDelay = 500 * time.Millisecond
  398. p.healthCheckMu.Lock()
  399. defer p.healthCheckMu.Unlock()
  400. if p.healthCheckTimer == nil {
  401. // Destroy is asynchronous so we give it time to actually remove itself from
  402. // the pool otherwise we might try to check the pool size too soon
  403. p.healthCheckTimer = time.AfterFunc(healthCheckDelay, func() {
  404. select {
  405. case <-p.closeChan:
  406. case p.healthCheckChan <- struct{}{}:
  407. default:
  408. }
  409. })
  410. return
  411. }
  412. p.healthCheckTimer.Reset(healthCheckDelay)
  413. }
  414. func (p *Pool) backgroundHealthCheck() {
  415. ticker := time.NewTicker(p.healthCheckPeriod)
  416. defer ticker.Stop()
  417. for {
  418. select {
  419. case <-p.closeChan:
  420. return
  421. case <-p.healthCheckChan:
  422. p.checkHealth()
  423. case <-ticker.C:
  424. p.checkHealth()
  425. }
  426. }
  427. }
  428. func (p *Pool) checkHealth() {
  429. for {
  430. // If checkMinConns failed we don't destroy any connections since we couldn't
  431. // even get to minConns
  432. if err := p.checkMinConns(); err != nil {
  433. // Should we log this error somewhere?
  434. break
  435. }
  436. if !p.checkConnsHealth() {
  437. // Since we didn't destroy any connections we can stop looping
  438. break
  439. }
  440. // Technically Destroy is asynchronous but 500ms should be enough for it to
  441. // remove it from the underlying pool
  442. select {
  443. case <-p.closeChan:
  444. return
  445. case <-time.After(500 * time.Millisecond):
  446. }
  447. }
  448. }
  449. // checkConnsHealth will check all idle connections, destroy a connection if
  450. // it's idle or too old, and returns true if any were destroyed
  451. func (p *Pool) checkConnsHealth() bool {
  452. var destroyed bool
  453. totalConns := p.Stat().TotalConns()
  454. resources := p.p.AcquireAllIdle()
  455. for _, res := range resources {
  456. // We're okay going under minConns if the lifetime is up
  457. if p.isExpired(res) && totalConns >= p.minConns {
  458. atomic.AddInt64(&p.lifetimeDestroyCount, 1)
  459. res.Destroy()
  460. destroyed = true
  461. // Since Destroy is async we manually decrement totalConns.
  462. totalConns--
  463. } else if res.IdleDuration() > p.maxConnIdleTime && totalConns > p.minConns {
  464. atomic.AddInt64(&p.idleDestroyCount, 1)
  465. res.Destroy()
  466. destroyed = true
  467. // Since Destroy is async we manually decrement totalConns.
  468. totalConns--
  469. } else {
  470. res.ReleaseUnused()
  471. }
  472. }
  473. return destroyed
  474. }
  475. func (p *Pool) checkMinConns() error {
  476. // TotalConns can include ones that are being destroyed but we should have
  477. // sleep(500ms) around all of the destroys to help prevent that from throwing
  478. // off this check
  479. // Create the number of connections needed to get to both minConns and minIdleConns
  480. toCreate := max(p.minConns-p.Stat().TotalConns(), p.minIdleConns-p.Stat().IdleConns())
  481. if toCreate > 0 {
  482. return p.createIdleResources(context.Background(), int(toCreate))
  483. }
  484. return nil
  485. }
  486. func (p *Pool) createIdleResources(parentCtx context.Context, targetResources int) error {
  487. ctx, cancel := context.WithCancel(parentCtx)
  488. defer cancel()
  489. errs := make(chan error, targetResources)
  490. for range targetResources {
  491. go func() {
  492. err := p.p.CreateResource(ctx)
  493. // Ignore ErrNotAvailable since it means that the pool has become full since we started creating resource.
  494. if err == puddle.ErrNotAvailable {
  495. err = nil
  496. }
  497. errs <- err
  498. }()
  499. }
  500. var firstError error
  501. for range targetResources {
  502. err := <-errs
  503. if err != nil && firstError == nil {
  504. cancel()
  505. firstError = err
  506. }
  507. }
  508. return firstError
  509. }
  510. // Acquire returns a connection (*Conn) from the Pool
  511. func (p *Pool) Acquire(ctx context.Context) (c *Conn, err error) {
  512. if p.acquireTracer != nil {
  513. ctx = p.acquireTracer.TraceAcquireStart(ctx, p, TraceAcquireStartData{})
  514. defer func() {
  515. var conn *pgx.Conn
  516. if c != nil {
  517. conn = c.Conn()
  518. }
  519. p.acquireTracer.TraceAcquireEnd(ctx, p, TraceAcquireEndData{Conn: conn, Err: err})
  520. }()
  521. }
  522. // Try to acquire from the connection pool up to maxConns + 1 times, so that
  523. // any that fatal errors would empty the pool and still at least try 1 fresh
  524. // connection.
  525. for range int(p.maxConns) + 1 {
  526. res, err := p.p.Acquire(ctx)
  527. if err != nil {
  528. return nil, err
  529. }
  530. cr := res.Value()
  531. shouldPingParams := ShouldPingParams{Conn: cr.conn, IdleDuration: res.IdleDuration()}
  532. if p.shouldPing(ctx, shouldPingParams) {
  533. pingCtx := ctx
  534. if p.pingTimeout > 0 {
  535. var cancel context.CancelFunc
  536. pingCtx, cancel = context.WithTimeout(ctx, p.pingTimeout)
  537. defer cancel()
  538. }
  539. err := cr.conn.Ping(pingCtx)
  540. if err != nil {
  541. res.Destroy()
  542. continue
  543. }
  544. }
  545. if p.prepareConn != nil {
  546. ok, err := p.prepareConn(ctx, cr.conn)
  547. if !ok {
  548. res.Destroy()
  549. }
  550. if err != nil {
  551. if ok {
  552. res.Release()
  553. }
  554. return nil, err
  555. }
  556. if !ok {
  557. continue
  558. }
  559. }
  560. return cr.getConn(p, res), nil
  561. }
  562. return nil, errors.New("pgxpool: detected infinite loop acquiring connection; likely bug in PrepareConn or BeforeAcquire hook")
  563. }
  564. // AcquireFunc acquires a *Conn and calls f with that *Conn. ctx will only affect the Acquire. It has no effect on the
  565. // call of f. The return value is either an error acquiring the *Conn or the return value of f. The *Conn is
  566. // automatically released after the call of f.
  567. func (p *Pool) AcquireFunc(ctx context.Context, f func(*Conn) error) error {
  568. conn, err := p.Acquire(ctx)
  569. if err != nil {
  570. return err
  571. }
  572. defer conn.Release()
  573. return f(conn)
  574. }
  575. // AcquireAllIdle atomically acquires all currently idle connections. Its intended use is for health check and
  576. // keep-alive functionality. It does not update pool statistics.
  577. func (p *Pool) AcquireAllIdle(ctx context.Context) []*Conn {
  578. resources := p.p.AcquireAllIdle()
  579. conns := make([]*Conn, 0, len(resources))
  580. for _, res := range resources {
  581. cr := res.Value()
  582. if p.prepareConn != nil {
  583. ok, err := p.prepareConn(ctx, cr.conn)
  584. if !ok || err != nil {
  585. res.Destroy()
  586. continue
  587. }
  588. }
  589. conns = append(conns, cr.getConn(p, res))
  590. }
  591. return conns
  592. }
  593. // Reset closes all connections, but leaves the pool open. It is intended for use when an error is detected that would
  594. // disrupt all connections (such as a network interruption or a server state change).
  595. //
  596. // It is safe to reset a pool while connections are checked out. Those connections will be closed when they are returned
  597. // to the pool.
  598. func (p *Pool) Reset() {
  599. p.p.Reset()
  600. }
  601. // Config returns a copy of config that was used to initialize this pool.
  602. func (p *Pool) Config() *Config { return p.config.Copy() }
  603. // Stat returns a pgxpool.Stat struct with a snapshot of Pool statistics.
  604. func (p *Pool) Stat() *Stat {
  605. return &Stat{
  606. s: p.p.Stat(),
  607. newConnsCount: atomic.LoadInt64(&p.newConnsCount),
  608. lifetimeDestroyCount: atomic.LoadInt64(&p.lifetimeDestroyCount),
  609. idleDestroyCount: atomic.LoadInt64(&p.idleDestroyCount),
  610. }
  611. }
  612. // Exec acquires a connection from the Pool and executes the given SQL.
  613. // SQL can be either a prepared statement name or an SQL string.
  614. // Arguments should be referenced positionally from the SQL string as $1, $2, etc.
  615. // The acquired connection is returned to the pool when the Exec function returns.
  616. func (p *Pool) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) {
  617. c, err := p.Acquire(ctx)
  618. if err != nil {
  619. return pgconn.CommandTag{}, err
  620. }
  621. defer c.Release()
  622. return c.Exec(ctx, sql, arguments...)
  623. }
  624. // Query acquires a connection and executes a query that returns pgx.Rows.
  625. // Arguments should be referenced positionally from the SQL string as $1, $2, etc.
  626. // See pgx.Rows documentation to close the returned Rows and return the acquired connection to the Pool.
  627. //
  628. // If there is an error, the returned pgx.Rows will be returned in an error state.
  629. // If preferred, ignore the error returned from Query and handle errors using the returned pgx.Rows.
  630. //
  631. // For extra control over how the query is executed, the types QuerySimpleProtocol, QueryResultFormats, and
  632. // QueryResultFormatsByOID may be used as the first args to control exactly how the query is executed. This is rarely
  633. // needed. See the documentation for those types for details.
  634. func (p *Pool) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
  635. c, err := p.Acquire(ctx)
  636. if err != nil {
  637. return errRows{err: err}, err
  638. }
  639. rows, err := c.Query(ctx, sql, args...)
  640. if err != nil {
  641. c.Release()
  642. return errRows{err: err}, err
  643. }
  644. return c.getPoolRows(rows), nil
  645. }
  646. // QueryRow acquires a connection and executes a query that is expected
  647. // to return at most one row (pgx.Row). Errors are deferred until pgx.Row's
  648. // Scan method is called. If the query selects no rows, pgx.Row's Scan will
  649. // return ErrNoRows. Otherwise, pgx.Row's Scan scans the first selected row
  650. // and discards the rest. The acquired connection is returned to the Pool when
  651. // pgx.Row's Scan method is called.
  652. //
  653. // Arguments should be referenced positionally from the SQL string as $1, $2, etc.
  654. //
  655. // For extra control over how the query is executed, the types QuerySimpleProtocol, QueryResultFormats, and
  656. // QueryResultFormatsByOID may be used as the first args to control exactly how the query is executed. This is rarely
  657. // needed. See the documentation for those types for details.
  658. func (p *Pool) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {
  659. c, err := p.Acquire(ctx)
  660. if err != nil {
  661. return errRow{err: err}
  662. }
  663. row := c.QueryRow(ctx, sql, args...)
  664. return c.getPoolRow(row)
  665. }
  666. func (p *Pool) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults {
  667. c, err := p.Acquire(ctx)
  668. if err != nil {
  669. return errBatchResults{err: err}
  670. }
  671. br := c.SendBatch(ctx, b)
  672. return &poolBatchResults{br: br, c: c}
  673. }
  674. // Begin acquires a connection from the Pool and starts a transaction. Unlike database/sql, the context only affects the begin command. i.e. there is no
  675. // auto-rollback on context cancellation. Begin initiates a transaction block without explicitly setting a transaction mode for the block (see BeginTx with TxOptions if transaction mode is required).
  676. // *pgxpool.Tx is returned, which implements the pgx.Tx interface.
  677. // Commit or Rollback must be called on the returned transaction to finalize the transaction block.
  678. func (p *Pool) Begin(ctx context.Context) (pgx.Tx, error) {
  679. return p.BeginTx(ctx, pgx.TxOptions{})
  680. }
  681. // BeginTx acquires a connection from the Pool and starts a transaction with pgx.TxOptions determining the transaction mode.
  682. // Unlike database/sql, the context only affects the begin command. i.e. there is no auto-rollback on context cancellation.
  683. // *pgxpool.Tx is returned, which implements the pgx.Tx interface.
  684. // Commit or Rollback must be called on the returned transaction to finalize the transaction block.
  685. func (p *Pool) BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error) {
  686. c, err := p.Acquire(ctx)
  687. if err != nil {
  688. return nil, err
  689. }
  690. t, err := c.BeginTx(ctx, txOptions)
  691. if err != nil {
  692. c.Release()
  693. return nil, err
  694. }
  695. return &Tx{t: t, c: c}, nil
  696. }
  697. func (p *Pool) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error) {
  698. c, err := p.Acquire(ctx)
  699. if err != nil {
  700. return 0, err
  701. }
  702. defer c.Release()
  703. return c.Conn().CopyFrom(ctx, tableName, columnNames, rowSrc)
  704. }
  705. // Ping acquires a connection from the Pool and executes an empty sql statement against it.
  706. // If the sql returns without error, the database Ping is considered successful, otherwise, the error is returned.
  707. func (p *Pool) Ping(ctx context.Context) error {
  708. c, err := p.Acquire(ctx)
  709. if err != nil {
  710. return err
  711. }
  712. defer c.Release()
  713. return c.Ping(ctx)
  714. }