db_prepared.go 918 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Copyright (C) 2025 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package sqlite
  7. import "github.com/jmoiron/sqlx"
  8. type txPreparedStmts struct {
  9. *sqlx.Tx
  10. stmts map[string]*sqlx.Stmt
  11. }
  12. func (p *txPreparedStmts) Preparex(query string) (*sqlx.Stmt, error) {
  13. if p.stmts == nil {
  14. p.stmts = make(map[string]*sqlx.Stmt)
  15. }
  16. stmt, ok := p.stmts[query]
  17. if ok {
  18. return stmt, nil
  19. }
  20. stmt, err := p.Tx.Preparex(query)
  21. if err != nil {
  22. return nil, wrap(err)
  23. }
  24. p.stmts[query] = stmt
  25. return stmt, nil
  26. }
  27. func (p *txPreparedStmts) Commit() error {
  28. for _, s := range p.stmts {
  29. s.Close()
  30. }
  31. return p.Tx.Commit()
  32. }
  33. func (p *txPreparedStmts) Rollback() error {
  34. for _, s := range p.stmts {
  35. s.Close()
  36. }
  37. return p.Tx.Rollback()
  38. }