promoteStatementsToCache prepares and caches statements that were used during the transaction but weren't already in the cache. This is called after successful commit.
()
| 429 | // promoteStatementsToCache prepares and caches statements that were used during the transaction |
| 430 | // but weren't already in the cache. This is called after successful commit. |
| 431 | func (t *Tx) promoteStatementsToCache() { |
| 432 | t.txMu.Lock() |
| 433 | queries := t.txStmts |
| 434 | t.txStmts = nil // Clear the map |
| 435 | t.txMu.Unlock() |
| 436 | |
| 437 | if len(queries) == 0 { |
| 438 | return |
| 439 | } |
| 440 | |
| 441 | // Prepare statements on the appropriate connection and add to cache |
| 442 | // Use a background context since transaction is already committed |
| 443 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 444 | defer cancel() |
| 445 | |
| 446 | for query := range queries { |
| 447 | boundQuery := t.db.bindQuery(query) |
| 448 | // Skip promotion during shutdown |
| 449 | if t.db.closing.Load() { |
| 450 | return |
| 451 | } |
| 452 | |
| 453 | t.db.stmtMu.RLock() |
| 454 | |
| 455 | // Determine which cache and connection to use based on transaction type |
| 456 | var stmts *ttlcache.Cache[string, *sql.Stmt] |
| 457 | var conn *sql.DB |
| 458 | if t.isWriteTx { |
| 459 | stmts = t.db.writerStmts |
| 460 | conn = t.db.writerConn |
| 461 | } else { |
| 462 | stmts = t.db.readerStmts |
| 463 | conn = t.db.readerPool |
| 464 | } |
| 465 | |
| 466 | if stmts == nil || conn == nil { |
| 467 | t.db.stmtMu.RUnlock() |
| 468 | return |
| 469 | } |
| 470 | |
| 471 | // Double-check it's not already cached (race condition protection) |
| 472 | if _, found := stmts.Get(boundQuery); found { |
| 473 | t.db.stmtMu.RUnlock() |
| 474 | continue |
| 475 | } |
| 476 | |
| 477 | // Prepare and cache the statement |
| 478 | stmt, err := conn.PrepareContext(ctx, boundQuery) |
| 479 | if err != nil { |
| 480 | t.db.stmtMu.RUnlock() |
| 481 | continue // silently skip - caching is best-effort |
| 482 | } |
| 483 | |
| 484 | stmts.Set(boundQuery, stmt, ttlcache.DefaultTTL) |
| 485 | t.db.stmtMu.RUnlock() |
| 486 | } |
| 487 | } |
| 488 |