conn.go 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  1. package pgx
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "database/sql"
  6. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/jackc/pgx/v5/internal/sanitize"
  13. "github.com/jackc/pgx/v5/internal/stmtcache"
  14. "github.com/jackc/pgx/v5/pgconn"
  15. "github.com/jackc/pgx/v5/pgtype"
  16. )
  17. // ConnConfig contains all the options used to establish a connection. It must be created by ParseConfig and
  18. // then it can be modified. A manually initialized ConnConfig will cause ConnectConfig to panic.
  19. type ConnConfig struct {
  20. pgconn.Config
  21. Tracer QueryTracer
  22. // Original connection string that was parsed into config.
  23. connString string
  24. // StatementCacheCapacity is maximum size of the statement cache used when executing a query with "cache_statement"
  25. // query exec mode.
  26. StatementCacheCapacity int
  27. // DescriptionCacheCapacity is the maximum size of the description cache used when executing a query with
  28. // "cache_describe" query exec mode.
  29. DescriptionCacheCapacity int
  30. // DefaultQueryExecMode controls the default mode for executing queries. By default pgx uses the extended protocol
  31. // and automatically prepares and caches prepared statements. However, this may be incompatible with proxies such as
  32. // PGBouncer. In this case it may be preferable to use QueryExecModeExec or QueryExecModeSimpleProtocol. The same
  33. // functionality can be controlled on a per query basis by passing a QueryExecMode as the first query argument.
  34. DefaultQueryExecMode QueryExecMode
  35. createdByParseConfig bool // Used to enforce created by ParseConfig rule.
  36. }
  37. // ParseConfigOptions contains options that control how a config is built such as getsslpassword.
  38. type ParseConfigOptions struct {
  39. pgconn.ParseConfigOptions
  40. }
  41. // Copy returns a deep copy of the config that is safe to use and modify.
  42. // The only exception is the tls.Config:
  43. // according to the tls.Config docs it must not be modified after creation.
  44. func (cc *ConnConfig) Copy() *ConnConfig {
  45. newConfig := new(ConnConfig)
  46. *newConfig = *cc
  47. newConfig.Config = *newConfig.Config.Copy()
  48. return newConfig
  49. }
  50. // ConnString returns the connection string as parsed by pgx.ParseConfig into pgx.ConnConfig.
  51. func (cc *ConnConfig) ConnString() string { return cc.connString }
  52. // Conn is a PostgreSQL connection handle. It is not safe for concurrent usage. Use a connection pool to manage access
  53. // to multiple database connections from multiple goroutines.
  54. type Conn struct {
  55. pgConn *pgconn.PgConn
  56. config *ConnConfig // config used when establishing this connection
  57. preparedStatements map[string]*pgconn.StatementDescription
  58. failedDescribeStatement string
  59. statementCache stmtcache.Cache
  60. descriptionCache stmtcache.Cache
  61. queryTracer QueryTracer
  62. batchTracer BatchTracer
  63. copyFromTracer CopyFromTracer
  64. prepareTracer PrepareTracer
  65. notifications []*pgconn.Notification
  66. doneChan chan struct{}
  67. closedChan chan error
  68. typeMap *pgtype.Map
  69. wbuf []byte
  70. eqb ExtendedQueryBuilder
  71. }
  72. // Identifier a PostgreSQL identifier or name. Identifiers can be composed of
  73. // multiple parts such as ["schema", "table"] or ["table", "column"].
  74. type Identifier []string
  75. // Sanitize returns a sanitized string safe for SQL interpolation.
  76. func (ident Identifier) Sanitize() string {
  77. parts := make([]string, len(ident))
  78. for i := range ident {
  79. s := strings.ReplaceAll(ident[i], string([]byte{0}), "")
  80. parts[i] = `"` + strings.ReplaceAll(s, `"`, `""`) + `"`
  81. }
  82. return strings.Join(parts, ".")
  83. }
  84. var (
  85. // ErrNoRows occurs when rows are expected but none are returned.
  86. ErrNoRows = newProxyErr(sql.ErrNoRows, "no rows in result set")
  87. // ErrTooManyRows occurs when more rows than expected are returned.
  88. ErrTooManyRows = errors.New("too many rows in result set")
  89. )
  90. func newProxyErr(background error, msg string) error {
  91. return &proxyError{
  92. msg: msg,
  93. background: background,
  94. }
  95. }
  96. type proxyError struct {
  97. msg string
  98. background error
  99. }
  100. func (err *proxyError) Error() string { return err.msg }
  101. func (err *proxyError) Unwrap() error { return err.background }
  102. var (
  103. errDisabledStatementCache = fmt.Errorf("cannot use QueryExecModeCacheStatement with disabled statement cache")
  104. errDisabledDescriptionCache = fmt.Errorf("cannot use QueryExecModeCacheDescribe with disabled description cache")
  105. )
  106. // Connect establishes a connection with a PostgreSQL server with a connection string. See
  107. // pgconn.Connect for details.
  108. func Connect(ctx context.Context, connString string) (*Conn, error) {
  109. connConfig, err := ParseConfig(connString)
  110. if err != nil {
  111. return nil, err
  112. }
  113. return connect(ctx, connConfig)
  114. }
  115. // ConnectWithOptions behaves exactly like Connect with the addition of options. At the present options is only used to
  116. // provide a GetSSLPassword function.
  117. func ConnectWithOptions(ctx context.Context, connString string, options ParseConfigOptions) (*Conn, error) {
  118. connConfig, err := ParseConfigWithOptions(connString, options)
  119. if err != nil {
  120. return nil, err
  121. }
  122. return connect(ctx, connConfig)
  123. }
  124. // ConnectConfig establishes a connection with a PostgreSQL server with a configuration struct.
  125. // connConfig must have been created by ParseConfig.
  126. func ConnectConfig(ctx context.Context, connConfig *ConnConfig) (*Conn, error) {
  127. // In general this improves safety. In particular avoid the config.Config.OnNotification mutation from affecting other
  128. // connections with the same config. See https://github.com/jackc/pgx/issues/618.
  129. connConfig = connConfig.Copy()
  130. return connect(ctx, connConfig)
  131. }
  132. // ParseConfigWithOptions behaves exactly as ParseConfig does with the addition of options. At the present options is
  133. // only used to provide a GetSSLPassword function.
  134. func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*ConnConfig, error) {
  135. config, err := pgconn.ParseConfigWithOptions(connString, options.ParseConfigOptions)
  136. if err != nil {
  137. return nil, err
  138. }
  139. statementCacheCapacity := 512
  140. if s, ok := config.RuntimeParams["statement_cache_capacity"]; ok {
  141. delete(config.RuntimeParams, "statement_cache_capacity")
  142. n, err := strconv.ParseInt(s, 10, 32)
  143. if err != nil {
  144. return nil, pgconn.NewParseConfigError(connString, "cannot parse statement_cache_capacity", err)
  145. }
  146. statementCacheCapacity = int(n)
  147. }
  148. descriptionCacheCapacity := 512
  149. if s, ok := config.RuntimeParams["description_cache_capacity"]; ok {
  150. delete(config.RuntimeParams, "description_cache_capacity")
  151. n, err := strconv.ParseInt(s, 10, 32)
  152. if err != nil {
  153. return nil, pgconn.NewParseConfigError(connString, "cannot parse description_cache_capacity", err)
  154. }
  155. descriptionCacheCapacity = int(n)
  156. }
  157. defaultQueryExecMode := QueryExecModeCacheStatement
  158. if s, ok := config.RuntimeParams["default_query_exec_mode"]; ok {
  159. delete(config.RuntimeParams, "default_query_exec_mode")
  160. switch s {
  161. case "cache_statement":
  162. defaultQueryExecMode = QueryExecModeCacheStatement
  163. case "cache_describe":
  164. defaultQueryExecMode = QueryExecModeCacheDescribe
  165. case "describe_exec":
  166. defaultQueryExecMode = QueryExecModeDescribeExec
  167. case "exec":
  168. defaultQueryExecMode = QueryExecModeExec
  169. case "simple_protocol":
  170. defaultQueryExecMode = QueryExecModeSimpleProtocol
  171. default:
  172. return nil, pgconn.NewParseConfigError(connString, "invalid default_query_exec_mode", err)
  173. }
  174. }
  175. connConfig := &ConnConfig{
  176. Config: *config,
  177. createdByParseConfig: true,
  178. StatementCacheCapacity: statementCacheCapacity,
  179. DescriptionCacheCapacity: descriptionCacheCapacity,
  180. DefaultQueryExecMode: defaultQueryExecMode,
  181. connString: connString,
  182. }
  183. return connConfig, nil
  184. }
  185. // ParseConfig creates a ConnConfig from a connection string. ParseConfig handles all options that [pgconn.ParseConfig]
  186. // does. In addition, it accepts the following options:
  187. //
  188. // - default_query_exec_mode.
  189. // Possible values: "cache_statement", "cache_describe", "describe_exec", "exec", and "simple_protocol". See
  190. // QueryExecMode constant documentation for the meaning of these values. Default: "cache_statement".
  191. //
  192. // - statement_cache_capacity.
  193. // The maximum size of the statement cache used when executing a query with "cache_statement" query exec mode.
  194. // Default: 512.
  195. //
  196. // - description_cache_capacity.
  197. // The maximum size of the description cache used when executing a query with "cache_describe" query exec mode.
  198. // Default: 512.
  199. func ParseConfig(connString string) (*ConnConfig, error) {
  200. return ParseConfigWithOptions(connString, ParseConfigOptions{})
  201. }
  202. // connect connects to a database. connect takes ownership of config. The caller must not use or access it again.
  203. func connect(ctx context.Context, config *ConnConfig) (c *Conn, err error) {
  204. if connectTracer, ok := config.Tracer.(ConnectTracer); ok {
  205. ctx = connectTracer.TraceConnectStart(ctx, TraceConnectStartData{ConnConfig: config})
  206. defer func() {
  207. connectTracer.TraceConnectEnd(ctx, TraceConnectEndData{Conn: c, Err: err})
  208. }()
  209. }
  210. // Default values are set in ParseConfig. Enforce initial creation by ParseConfig rather than setting defaults from
  211. // zero values.
  212. if !config.createdByParseConfig {
  213. panic("config must be created by ParseConfig")
  214. }
  215. c = &Conn{
  216. config: config,
  217. typeMap: pgtype.NewMap(),
  218. queryTracer: config.Tracer,
  219. }
  220. if t, ok := c.queryTracer.(BatchTracer); ok {
  221. c.batchTracer = t
  222. }
  223. if t, ok := c.queryTracer.(CopyFromTracer); ok {
  224. c.copyFromTracer = t
  225. }
  226. if t, ok := c.queryTracer.(PrepareTracer); ok {
  227. c.prepareTracer = t
  228. }
  229. // Only install pgx notification system if no other callback handler is present.
  230. if config.Config.OnNotification == nil {
  231. config.Config.OnNotification = c.bufferNotifications
  232. }
  233. c.pgConn, err = pgconn.ConnectConfig(ctx, &config.Config)
  234. if err != nil {
  235. return nil, err
  236. }
  237. c.preparedStatements = make(map[string]*pgconn.StatementDescription)
  238. c.doneChan = make(chan struct{})
  239. c.closedChan = make(chan error)
  240. c.wbuf = make([]byte, 0, 1024)
  241. if c.config.StatementCacheCapacity > 0 {
  242. c.statementCache = stmtcache.NewLRUCache(c.config.StatementCacheCapacity)
  243. }
  244. if c.config.DescriptionCacheCapacity > 0 {
  245. c.descriptionCache = stmtcache.NewLRUCache(c.config.DescriptionCacheCapacity)
  246. }
  247. return c, nil
  248. }
  249. // Close closes a connection. It is safe to call Close on an already closed
  250. // connection.
  251. func (c *Conn) Close(ctx context.Context) error {
  252. if c.IsClosed() {
  253. return nil
  254. }
  255. err := c.pgConn.Close(ctx)
  256. return err
  257. }
  258. // Prepare creates a prepared statement with name and sql. sql can contain placeholders for bound parameters. These
  259. // placeholders are referenced positionally as $1, $2, etc. name can be used instead of sql with Query, QueryRow, and
  260. // Exec to execute the statement. It can also be used with Batch.Queue.
  261. //
  262. // The underlying PostgreSQL identifier for the prepared statement will be name if name != sql or a digest of sql if
  263. // name == sql.
  264. //
  265. // Prepare is idempotent; i.e. it is safe to call Prepare multiple times with the same name and sql arguments. This
  266. // allows a code path to Prepare and Query/Exec without concern for if the statement has already been prepared.
  267. func (c *Conn) Prepare(ctx context.Context, name, sql string) (sd *pgconn.StatementDescription, err error) {
  268. if c.failedDescribeStatement != "" {
  269. err = c.Deallocate(ctx, c.failedDescribeStatement)
  270. if err != nil {
  271. return nil, fmt.Errorf("failed to deallocate previously failed statement %q: %w", c.failedDescribeStatement, err)
  272. }
  273. c.failedDescribeStatement = ""
  274. }
  275. if c.prepareTracer != nil {
  276. ctx = c.prepareTracer.TracePrepareStart(ctx, c, TracePrepareStartData{Name: name, SQL: sql})
  277. }
  278. if name != "" {
  279. var ok bool
  280. if sd, ok = c.preparedStatements[name]; ok && sd.SQL == sql {
  281. if c.prepareTracer != nil {
  282. c.prepareTracer.TracePrepareEnd(ctx, c, TracePrepareEndData{AlreadyPrepared: true})
  283. }
  284. return sd, nil
  285. }
  286. }
  287. if c.prepareTracer != nil {
  288. defer func() {
  289. c.prepareTracer.TracePrepareEnd(ctx, c, TracePrepareEndData{Err: err})
  290. }()
  291. }
  292. var psName, psKey string
  293. if name == sql {
  294. digest := sha256.Sum256([]byte(sql))
  295. psName = "stmt_" + hex.EncodeToString(digest[0:24])
  296. psKey = sql
  297. } else {
  298. psName = name
  299. psKey = name
  300. }
  301. sd, err = c.pgConn.Prepare(ctx, psName, sql, nil)
  302. if err != nil {
  303. var pErr *pgconn.PrepareError
  304. if errors.As(err, &pErr) {
  305. c.failedDescribeStatement = psKey
  306. }
  307. return nil, err
  308. }
  309. if psKey != "" {
  310. c.preparedStatements[psKey] = sd
  311. }
  312. return sd, nil
  313. }
  314. // Deallocate releases a prepared statement. Calling Deallocate on a non-existent prepared statement will succeed.
  315. func (c *Conn) Deallocate(ctx context.Context, name string) error {
  316. var psName string
  317. sd := c.preparedStatements[name]
  318. if sd != nil {
  319. psName = sd.Name
  320. } else {
  321. psName = name
  322. }
  323. err := c.pgConn.Deallocate(ctx, psName)
  324. if err != nil {
  325. return err
  326. }
  327. if sd != nil {
  328. delete(c.preparedStatements, name)
  329. }
  330. return nil
  331. }
  332. // DeallocateAll releases all previously prepared statements from the server and client, where it also resets the statement and description cache.
  333. func (c *Conn) DeallocateAll(ctx context.Context) error {
  334. c.preparedStatements = map[string]*pgconn.StatementDescription{}
  335. if c.config.StatementCacheCapacity > 0 {
  336. c.statementCache = stmtcache.NewLRUCache(c.config.StatementCacheCapacity)
  337. }
  338. if c.config.DescriptionCacheCapacity > 0 {
  339. c.descriptionCache = stmtcache.NewLRUCache(c.config.DescriptionCacheCapacity)
  340. }
  341. _, err := c.pgConn.Exec(ctx, "deallocate all").ReadAll()
  342. return err
  343. }
  344. func (c *Conn) bufferNotifications(_ *pgconn.PgConn, n *pgconn.Notification) {
  345. c.notifications = append(c.notifications, n)
  346. }
  347. // WaitForNotification waits for a PostgreSQL notification. It wraps the underlying pgconn notification system in a
  348. // slightly more convenient form.
  349. func (c *Conn) WaitForNotification(ctx context.Context) (*pgconn.Notification, error) {
  350. var n *pgconn.Notification
  351. // Return already received notification immediately
  352. if len(c.notifications) > 0 {
  353. n = c.notifications[0]
  354. c.notifications = c.notifications[1:]
  355. return n, nil
  356. }
  357. err := c.pgConn.WaitForNotification(ctx)
  358. if len(c.notifications) > 0 {
  359. n = c.notifications[0]
  360. c.notifications = c.notifications[1:]
  361. }
  362. return n, err
  363. }
  364. // IsClosed reports if the connection has been closed.
  365. func (c *Conn) IsClosed() bool {
  366. return c.pgConn.IsClosed()
  367. }
  368. func (c *Conn) die() {
  369. if c.IsClosed() {
  370. return
  371. }
  372. ctx, cancel := context.WithCancel(context.Background())
  373. cancel() // force immediate hard cancel
  374. c.pgConn.Close(ctx)
  375. }
  376. func quoteIdentifier(s string) string {
  377. return `"` + strings.ReplaceAll(s, `"`, `""`) + `"`
  378. }
  379. // Ping delegates to the underlying *pgconn.PgConn.Ping.
  380. func (c *Conn) Ping(ctx context.Context) error {
  381. return c.pgConn.Ping(ctx)
  382. }
  383. // PgConn returns the underlying *pgconn.PgConn. This is an escape hatch method that allows lower level access to the
  384. // PostgreSQL connection than pgx exposes.
  385. //
  386. // It is strongly recommended that the connection be idle (no in-progress queries) before the underlying *pgconn.PgConn
  387. // is used and the connection must be returned to the same state before any *pgx.Conn methods are again used.
  388. func (c *Conn) PgConn() *pgconn.PgConn { return c.pgConn }
  389. // TypeMap returns the connection info used for this connection.
  390. func (c *Conn) TypeMap() *pgtype.Map { return c.typeMap }
  391. // Config returns a copy of config that was used to establish this connection.
  392. func (c *Conn) Config() *ConnConfig { return c.config.Copy() }
  393. // Exec executes sql. sql can be either a prepared statement name or an SQL string. arguments should be referenced
  394. // positionally from the sql string as $1, $2, etc.
  395. func (c *Conn) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) {
  396. if c.queryTracer != nil {
  397. ctx = c.queryTracer.TraceQueryStart(ctx, c, TraceQueryStartData{SQL: sql, Args: arguments})
  398. }
  399. if err := c.deallocateInvalidatedCachedStatements(ctx); err != nil {
  400. return pgconn.CommandTag{}, err
  401. }
  402. commandTag, err := c.exec(ctx, sql, arguments...)
  403. if c.queryTracer != nil {
  404. c.queryTracer.TraceQueryEnd(ctx, c, TraceQueryEndData{CommandTag: commandTag, Err: err})
  405. }
  406. return commandTag, err
  407. }
  408. func (c *Conn) exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error) {
  409. mode := c.config.DefaultQueryExecMode
  410. var queryRewriter QueryRewriter
  411. optionLoop:
  412. for len(arguments) > 0 {
  413. switch arg := arguments[0].(type) {
  414. case QueryExecMode:
  415. mode = arg
  416. arguments = arguments[1:]
  417. case QueryRewriter:
  418. queryRewriter = arg
  419. arguments = arguments[1:]
  420. default:
  421. break optionLoop
  422. }
  423. }
  424. if queryRewriter != nil {
  425. sql, arguments, err = queryRewriter.RewriteQuery(ctx, c, sql, arguments)
  426. if err != nil {
  427. return pgconn.CommandTag{}, fmt.Errorf("rewrite query failed: %w", err)
  428. }
  429. }
  430. // Always use simple protocol when there are no arguments.
  431. if len(arguments) == 0 {
  432. mode = QueryExecModeSimpleProtocol
  433. }
  434. defer func() {
  435. if err != nil {
  436. if sc := c.statementCache; sc != nil {
  437. sc.Invalidate(sql)
  438. }
  439. if sc := c.descriptionCache; sc != nil {
  440. sc.Invalidate(sql)
  441. }
  442. }
  443. }()
  444. if sd, ok := c.preparedStatements[sql]; ok {
  445. return c.execPrepared(ctx, sd, arguments)
  446. }
  447. switch mode {
  448. case QueryExecModeCacheStatement:
  449. if c.statementCache == nil {
  450. return pgconn.CommandTag{}, errDisabledStatementCache
  451. }
  452. sd := c.statementCache.Get(sql)
  453. if sd == nil {
  454. sd, err = c.Prepare(ctx, stmtcache.StatementName(sql), sql)
  455. if err != nil {
  456. return pgconn.CommandTag{}, err
  457. }
  458. c.statementCache.Put(sd)
  459. }
  460. return c.execPrepared(ctx, sd, arguments)
  461. case QueryExecModeCacheDescribe:
  462. if c.descriptionCache == nil {
  463. return pgconn.CommandTag{}, errDisabledDescriptionCache
  464. }
  465. sd := c.descriptionCache.Get(sql)
  466. if sd == nil {
  467. sd, err = c.Prepare(ctx, "", sql)
  468. if err != nil {
  469. return pgconn.CommandTag{}, err
  470. }
  471. c.descriptionCache.Put(sd)
  472. }
  473. return c.execParams(ctx, sd, arguments)
  474. case QueryExecModeDescribeExec:
  475. sd, err := c.Prepare(ctx, "", sql)
  476. if err != nil {
  477. return pgconn.CommandTag{}, err
  478. }
  479. return c.execPrepared(ctx, sd, arguments)
  480. case QueryExecModeExec:
  481. return c.execSQLParams(ctx, sql, arguments)
  482. case QueryExecModeSimpleProtocol:
  483. return c.execSimpleProtocol(ctx, sql, arguments)
  484. default:
  485. return pgconn.CommandTag{}, fmt.Errorf("unknown QueryExecMode: %v", mode)
  486. }
  487. }
  488. func (c *Conn) execSimpleProtocol(ctx context.Context, sql string, arguments []any) (commandTag pgconn.CommandTag, err error) {
  489. if len(arguments) > 0 {
  490. sql, err = c.sanitizeForSimpleQuery(sql, arguments...)
  491. if err != nil {
  492. return pgconn.CommandTag{}, err
  493. }
  494. }
  495. mrr := c.pgConn.Exec(ctx, sql)
  496. for mrr.NextResult() {
  497. commandTag, _ = mrr.ResultReader().Close()
  498. }
  499. err = mrr.Close()
  500. return commandTag, err
  501. }
  502. func (c *Conn) execParams(ctx context.Context, sd *pgconn.StatementDescription, arguments []any) (pgconn.CommandTag, error) {
  503. err := c.eqb.Build(c.typeMap, sd, arguments)
  504. if err != nil {
  505. return pgconn.CommandTag{}, err
  506. }
  507. result := c.pgConn.ExecParams(ctx, sd.SQL, c.eqb.ParamValues, sd.ParamOIDs, c.eqb.ParamFormats, c.eqb.ResultFormats).Read()
  508. c.eqb.reset() // Allow c.eqb internal memory to be GC'ed as soon as possible.
  509. return result.CommandTag, result.Err
  510. }
  511. func (c *Conn) execPrepared(ctx context.Context, sd *pgconn.StatementDescription, arguments []any) (pgconn.CommandTag, error) {
  512. err := c.eqb.Build(c.typeMap, sd, arguments)
  513. if err != nil {
  514. return pgconn.CommandTag{}, err
  515. }
  516. result := c.pgConn.ExecPrepared(ctx, sd.Name, c.eqb.ParamValues, c.eqb.ParamFormats, c.eqb.ResultFormats).Read()
  517. c.eqb.reset() // Allow c.eqb internal memory to be GC'ed as soon as possible.
  518. return result.CommandTag, result.Err
  519. }
  520. func (c *Conn) execSQLParams(ctx context.Context, sql string, args []any) (pgconn.CommandTag, error) {
  521. err := c.eqb.Build(c.typeMap, nil, args)
  522. if err != nil {
  523. return pgconn.CommandTag{}, err
  524. }
  525. result := c.pgConn.ExecParams(ctx, sql, c.eqb.ParamValues, nil, c.eqb.ParamFormats, c.eqb.ResultFormats).Read()
  526. c.eqb.reset() // Allow c.eqb internal memory to be GC'ed as soon as possible.
  527. return result.CommandTag, result.Err
  528. }
  529. func (c *Conn) getRows(ctx context.Context, sql string, args []any) *baseRows {
  530. r := &baseRows{}
  531. r.ctx = ctx
  532. r.queryTracer = c.queryTracer
  533. r.typeMap = c.typeMap
  534. r.startTime = time.Now()
  535. r.sql = sql
  536. r.args = args
  537. r.conn = c
  538. return r
  539. }
  540. type QueryExecMode int32
  541. const (
  542. _ QueryExecMode = iota
  543. // Automatically prepare and cache statements. This uses the extended protocol. Queries are executed in a single round
  544. // trip after the statement is cached. This is the default. If the database schema is modified or the search_path is
  545. // changed after a statement is cached then the first execution of a previously cached query may fail. e.g. If the
  546. // number of columns returned by a "SELECT *" changes or the type of a column is changed.
  547. QueryExecModeCacheStatement
  548. // Cache statement descriptions (i.e. argument and result types) and assume they do not change. This uses the extended
  549. // protocol. Queries are executed in a single round trip after the description is cached. If the database schema is
  550. // modified or the search_path is changed after a statement is cached then the first execution of a previously cached
  551. // query may fail. e.g. If the number of columns returned by a "SELECT *" changes or the type of a column is changed.
  552. QueryExecModeCacheDescribe
  553. // Get the statement description on every execution. This uses the extended protocol. Queries require two round trips
  554. // to execute. It does not use named prepared statements. But it does use the unnamed prepared statement to get the
  555. // statement description on the first round trip and then uses it to execute the query on the second round trip. This
  556. // may cause problems with connection poolers that switch the underlying connection between round trips. It is safe
  557. // even when the database schema is modified concurrently.
  558. QueryExecModeDescribeExec
  559. // Assume the PostgreSQL query parameter types based on the Go type of the arguments. This uses the extended protocol
  560. // with text formatted parameters and results. Queries are executed in a single round trip. Type mappings can be
  561. // registered with pgtype.Map.RegisterDefaultPgType. Queries will be rejected that have arguments that are
  562. // unregistered or ambiguous. e.g. A map[string]string may have the PostgreSQL type json or hstore. Modes that know
  563. // the PostgreSQL type can use a map[string]string directly as an argument. This mode cannot.
  564. //
  565. // On rare occasions user defined types may behave differently when encoded in the text format instead of the binary
  566. // format. For example, this could happen if a "type RomanNumeral int32" implements fmt.Stringer to format integers as
  567. // Roman numerals (e.g. 7 is VII). The binary format would properly encode the integer 7 as the binary value for 7.
  568. // But the text format would encode the integer 7 as the string "VII". As QueryExecModeExec uses the text format, it
  569. // is possible that changing query mode from another mode to QueryExecModeExec could change the behavior of the query.
  570. // This should not occur with types pgx supports directly and can be avoided by registering the types with
  571. // pgtype.Map.RegisterDefaultPgType and implementing the appropriate type interfaces. In the cas of RomanNumeral, it
  572. // should implement pgtype.Int64Valuer.
  573. QueryExecModeExec
  574. // Use the simple protocol. Assume the PostgreSQL query parameter types based on the Go type of the arguments. This is
  575. // especially significant for []byte values. []byte values are encoded as PostgreSQL bytea. string must be used
  576. // instead for text type values including json and jsonb. Type mappings can be registered with
  577. // pgtype.Map.RegisterDefaultPgType. Queries will be rejected that have arguments that are unregistered or ambiguous.
  578. // e.g. A map[string]string may have the PostgreSQL type json or hstore. Modes that know the PostgreSQL type can use a
  579. // map[string]string directly as an argument. This mode cannot. Queries are executed in a single round trip.
  580. //
  581. // QueryExecModeSimpleProtocol should have the user application visible behavior as QueryExecModeExec. This includes
  582. // the warning regarding differences in text format and binary format encoding with user defined types. There may be
  583. // other minor exceptions such as behavior when multiple result returning queries are erroneously sent in a single
  584. // string.
  585. //
  586. // QueryExecModeSimpleProtocol uses client side parameter interpolation. All values are quoted and escaped. Prefer
  587. // QueryExecModeExec over QueryExecModeSimpleProtocol whenever possible. In general QueryExecModeSimpleProtocol should
  588. // only be used if connecting to a proxy server, connection pool server, or non-PostgreSQL server that does not
  589. // support the extended protocol.
  590. QueryExecModeSimpleProtocol
  591. )
  592. func (m QueryExecMode) String() string {
  593. switch m {
  594. case QueryExecModeCacheStatement:
  595. return "cache statement"
  596. case QueryExecModeCacheDescribe:
  597. return "cache describe"
  598. case QueryExecModeDescribeExec:
  599. return "describe exec"
  600. case QueryExecModeExec:
  601. return "exec"
  602. case QueryExecModeSimpleProtocol:
  603. return "simple protocol"
  604. default:
  605. return "invalid"
  606. }
  607. }
  608. // QueryResultFormats controls the result format (text=0, binary=1) of a query by result column position.
  609. type QueryResultFormats []int16
  610. // QueryResultFormatsByOID controls the result format (text=0, binary=1) of a query by the result column OID.
  611. type QueryResultFormatsByOID map[uint32]int16
  612. // QueryRewriter rewrites a query when used as the first arguments to a query method.
  613. type QueryRewriter interface {
  614. RewriteQuery(ctx context.Context, conn *Conn, sql string, args []any) (newSQL string, newArgs []any, err error)
  615. }
  616. // Query sends a query to the server and returns a Rows to read the results. Only errors encountered sending the query
  617. // and initializing Rows will be returned. Err() on the returned Rows must be checked after the Rows is closed to
  618. // determine if the query executed successfully.
  619. //
  620. // The returned Rows must be closed before the connection can be used again. It is safe to attempt to read from the
  621. // returned Rows even if an error is returned. The error will be the available in rows.Err() after rows are closed. It
  622. // is allowed to ignore the error returned from Query and handle it in Rows.
  623. //
  624. // It is possible for a call of FieldDescriptions on the returned Rows to return nil even if the Query call did not
  625. // return an error.
  626. //
  627. // It is possible for a query to return one or more rows before encountering an error. In most cases the rows should be
  628. // collected before processing rather than processed while receiving each row. This avoids the possibility of the
  629. // application processing rows from a query that the server rejected. The CollectRows function is useful here.
  630. //
  631. // An implementor of QueryRewriter may be passed as the first element of args. It can rewrite the sql and change or
  632. // replace args. For example, NamedArgs is QueryRewriter that implements named arguments.
  633. //
  634. // For extra control over how the query is executed, the types QueryExecMode, QueryResultFormats, and
  635. // QueryResultFormatsByOID may be used as the first args to control exactly how the query is executed. This is rarely
  636. // needed. See the documentation for those types for details.
  637. func (c *Conn) Query(ctx context.Context, sql string, args ...any) (Rows, error) {
  638. if c.queryTracer != nil {
  639. ctx = c.queryTracer.TraceQueryStart(ctx, c, TraceQueryStartData{SQL: sql, Args: args})
  640. }
  641. if err := c.deallocateInvalidatedCachedStatements(ctx); err != nil {
  642. if c.queryTracer != nil {
  643. c.queryTracer.TraceQueryEnd(ctx, c, TraceQueryEndData{Err: err})
  644. }
  645. return &baseRows{err: err, closed: true}, err
  646. }
  647. var resultFormats QueryResultFormats
  648. var resultFormatsByOID QueryResultFormatsByOID
  649. mode := c.config.DefaultQueryExecMode
  650. var queryRewriter QueryRewriter
  651. optionLoop:
  652. for len(args) > 0 {
  653. switch arg := args[0].(type) {
  654. case QueryResultFormats:
  655. resultFormats = arg
  656. args = args[1:]
  657. case QueryResultFormatsByOID:
  658. resultFormatsByOID = arg
  659. args = args[1:]
  660. case QueryExecMode:
  661. mode = arg
  662. args = args[1:]
  663. case QueryRewriter:
  664. queryRewriter = arg
  665. args = args[1:]
  666. default:
  667. break optionLoop
  668. }
  669. }
  670. if queryRewriter != nil {
  671. var err error
  672. originalSQL := sql
  673. originalArgs := args
  674. sql, args, err = queryRewriter.RewriteQuery(ctx, c, sql, args)
  675. if err != nil {
  676. rows := c.getRows(ctx, originalSQL, originalArgs)
  677. err = fmt.Errorf("rewrite query failed: %w", err)
  678. rows.fatal(err)
  679. return rows, err
  680. }
  681. }
  682. // Bypass any statement caching.
  683. if sql == "" {
  684. mode = QueryExecModeSimpleProtocol
  685. }
  686. c.eqb.reset()
  687. rows := c.getRows(ctx, sql, args)
  688. var err error
  689. sd, explicitPreparedStatement := c.preparedStatements[sql]
  690. if sd != nil || mode == QueryExecModeCacheStatement || mode == QueryExecModeCacheDescribe || mode == QueryExecModeDescribeExec {
  691. if sd == nil {
  692. sd, err = c.getStatementDescription(ctx, mode, sql)
  693. if err != nil {
  694. rows.fatal(err)
  695. return rows, err
  696. }
  697. }
  698. if len(sd.ParamOIDs) != len(args) {
  699. rows.fatal(fmt.Errorf("expected %d arguments, got %d", len(sd.ParamOIDs), len(args)))
  700. return rows, rows.err
  701. }
  702. rows.sql = sd.SQL
  703. err = c.eqb.Build(c.typeMap, sd, args)
  704. if err != nil {
  705. rows.fatal(err)
  706. return rows, rows.err
  707. }
  708. if resultFormatsByOID != nil {
  709. resultFormats = make([]int16, len(sd.Fields))
  710. for i := range resultFormats {
  711. resultFormats[i] = resultFormatsByOID[uint32(sd.Fields[i].DataTypeOID)]
  712. }
  713. }
  714. if resultFormats == nil {
  715. resultFormats = c.eqb.ResultFormats
  716. }
  717. if !explicitPreparedStatement && mode == QueryExecModeCacheDescribe {
  718. rows.resultReader = c.pgConn.ExecParams(ctx, sql, c.eqb.ParamValues, sd.ParamOIDs, c.eqb.ParamFormats, resultFormats)
  719. } else {
  720. rows.resultReader = c.pgConn.ExecPrepared(ctx, sd.Name, c.eqb.ParamValues, c.eqb.ParamFormats, resultFormats)
  721. }
  722. } else if mode == QueryExecModeExec {
  723. err := c.eqb.Build(c.typeMap, nil, args)
  724. if err != nil {
  725. rows.fatal(err)
  726. return rows, rows.err
  727. }
  728. rows.resultReader = c.pgConn.ExecParams(ctx, sql, c.eqb.ParamValues, nil, c.eqb.ParamFormats, c.eqb.ResultFormats)
  729. } else if mode == QueryExecModeSimpleProtocol {
  730. sql, err = c.sanitizeForSimpleQuery(sql, args...)
  731. if err != nil {
  732. rows.fatal(err)
  733. return rows, err
  734. }
  735. mrr := c.pgConn.Exec(ctx, sql)
  736. if mrr.NextResult() {
  737. rows.resultReader = mrr.ResultReader()
  738. rows.multiResultReader = mrr
  739. } else {
  740. err = mrr.Close()
  741. rows.fatal(err)
  742. return rows, err
  743. }
  744. return rows, nil
  745. } else {
  746. err = fmt.Errorf("unknown QueryExecMode: %v", mode)
  747. rows.fatal(err)
  748. return rows, rows.err
  749. }
  750. c.eqb.reset() // Allow c.eqb internal memory to be GC'ed as soon as possible.
  751. return rows, rows.err
  752. }
  753. // getStatementDescription returns the statement description of the sql query
  754. // according to the given mode.
  755. //
  756. // If the mode is one that doesn't require to know the param and result OIDs
  757. // then nil is returned without error.
  758. func (c *Conn) getStatementDescription(
  759. ctx context.Context,
  760. mode QueryExecMode,
  761. sql string,
  762. ) (sd *pgconn.StatementDescription, err error) {
  763. switch mode {
  764. case QueryExecModeCacheStatement:
  765. if c.statementCache == nil {
  766. return nil, errDisabledStatementCache
  767. }
  768. sd = c.statementCache.Get(sql)
  769. if sd == nil {
  770. sd, err = c.Prepare(ctx, stmtcache.StatementName(sql), sql)
  771. if err != nil {
  772. return nil, err
  773. }
  774. c.statementCache.Put(sd)
  775. }
  776. case QueryExecModeCacheDescribe:
  777. if c.descriptionCache == nil {
  778. return nil, errDisabledDescriptionCache
  779. }
  780. sd = c.descriptionCache.Get(sql)
  781. if sd == nil {
  782. sd, err = c.Prepare(ctx, "", sql)
  783. if err != nil {
  784. return nil, err
  785. }
  786. c.descriptionCache.Put(sd)
  787. }
  788. case QueryExecModeDescribeExec:
  789. return c.Prepare(ctx, "", sql)
  790. }
  791. return sd, err
  792. }
  793. // QueryRow is a convenience wrapper over Query. Any error that occurs while
  794. // querying is deferred until calling Scan on the returned Row. That Row will
  795. // error with ErrNoRows if no rows are returned.
  796. func (c *Conn) QueryRow(ctx context.Context, sql string, args ...any) Row {
  797. rows, _ := c.Query(ctx, sql, args...)
  798. return (*connRow)(rows.(*baseRows))
  799. }
  800. // SendBatch sends all queued queries to the server at once. All queries are run in an implicit transaction unless
  801. // explicit transaction control statements are executed. The returned BatchResults must be closed before the connection
  802. // is used again.
  803. //
  804. // Depending on the QueryExecMode, all queries may be prepared before any are executed. This means that creating a table
  805. // and using it in a subsequent query in the same batch can fail.
  806. func (c *Conn) SendBatch(ctx context.Context, b *Batch) (br BatchResults) {
  807. if len(b.QueuedQueries) == 0 {
  808. return &emptyBatchResults{conn: c}
  809. }
  810. if c.batchTracer != nil {
  811. ctx = c.batchTracer.TraceBatchStart(ctx, c, TraceBatchStartData{Batch: b})
  812. defer func() {
  813. err := br.(interface{ earlyError() error }).earlyError()
  814. if err != nil {
  815. c.batchTracer.TraceBatchEnd(ctx, c, TraceBatchEndData{Err: err})
  816. }
  817. }()
  818. }
  819. if err := c.deallocateInvalidatedCachedStatements(ctx); err != nil {
  820. return &batchResults{ctx: ctx, conn: c, err: err}
  821. }
  822. for _, bi := range b.QueuedQueries {
  823. var queryRewriter QueryRewriter
  824. sql := bi.SQL
  825. arguments := bi.Arguments
  826. optionLoop:
  827. for len(arguments) > 0 {
  828. // Update Batch.Queue function comment when additional options are implemented
  829. switch arg := arguments[0].(type) {
  830. case QueryRewriter:
  831. queryRewriter = arg
  832. arguments = arguments[1:]
  833. default:
  834. break optionLoop
  835. }
  836. }
  837. if queryRewriter != nil {
  838. var err error
  839. sql, arguments, err = queryRewriter.RewriteQuery(ctx, c, sql, arguments)
  840. if err != nil {
  841. return &batchResults{ctx: ctx, conn: c, err: fmt.Errorf("rewrite query failed: %w", err)}
  842. }
  843. }
  844. bi.SQL = sql
  845. bi.Arguments = arguments
  846. }
  847. // TODO: changing mode per batch? Update Batch.Queue function comment when implemented
  848. mode := c.config.DefaultQueryExecMode
  849. if mode == QueryExecModeSimpleProtocol {
  850. return c.sendBatchQueryExecModeSimpleProtocol(ctx, b)
  851. }
  852. // All other modes use extended protocol and thus can use prepared statements.
  853. for _, bi := range b.QueuedQueries {
  854. if sd, ok := c.preparedStatements[bi.SQL]; ok {
  855. bi.sd = sd
  856. }
  857. }
  858. switch mode {
  859. case QueryExecModeExec:
  860. return c.sendBatchQueryExecModeExec(ctx, b)
  861. case QueryExecModeCacheStatement:
  862. return c.sendBatchQueryExecModeCacheStatement(ctx, b)
  863. case QueryExecModeCacheDescribe:
  864. return c.sendBatchQueryExecModeCacheDescribe(ctx, b)
  865. case QueryExecModeDescribeExec:
  866. return c.sendBatchQueryExecModeDescribeExec(ctx, b)
  867. default:
  868. panic("unknown QueryExecMode")
  869. }
  870. }
  871. func (c *Conn) sendBatchQueryExecModeSimpleProtocol(ctx context.Context, b *Batch) *batchResults {
  872. var sb strings.Builder
  873. for i, bi := range b.QueuedQueries {
  874. if i > 0 {
  875. sb.WriteByte(';')
  876. }
  877. sql, err := c.sanitizeForSimpleQuery(bi.SQL, bi.Arguments...)
  878. if err != nil {
  879. return &batchResults{ctx: ctx, conn: c, err: err}
  880. }
  881. sb.WriteString(sql)
  882. }
  883. mrr := c.pgConn.Exec(ctx, sb.String())
  884. return &batchResults{
  885. ctx: ctx,
  886. conn: c,
  887. mrr: mrr,
  888. b: b,
  889. qqIdx: 0,
  890. }
  891. }
  892. func (c *Conn) sendBatchQueryExecModeExec(ctx context.Context, b *Batch) *batchResults {
  893. batch := &pgconn.Batch{}
  894. for _, bi := range b.QueuedQueries {
  895. sd := bi.sd
  896. if sd != nil {
  897. err := c.eqb.Build(c.typeMap, sd, bi.Arguments)
  898. if err != nil {
  899. return &batchResults{ctx: ctx, conn: c, err: err}
  900. }
  901. batch.ExecPrepared(sd.Name, c.eqb.ParamValues, c.eqb.ParamFormats, c.eqb.ResultFormats)
  902. } else {
  903. err := c.eqb.Build(c.typeMap, nil, bi.Arguments)
  904. if err != nil {
  905. return &batchResults{ctx: ctx, conn: c, err: err}
  906. }
  907. batch.ExecParams(bi.SQL, c.eqb.ParamValues, nil, c.eqb.ParamFormats, c.eqb.ResultFormats)
  908. }
  909. }
  910. c.eqb.reset() // Allow c.eqb internal memory to be GC'ed as soon as possible.
  911. mrr := c.pgConn.ExecBatch(ctx, batch)
  912. return &batchResults{
  913. ctx: ctx,
  914. conn: c,
  915. mrr: mrr,
  916. b: b,
  917. qqIdx: 0,
  918. }
  919. }
  920. func (c *Conn) sendBatchQueryExecModeCacheStatement(ctx context.Context, b *Batch) (pbr *pipelineBatchResults) {
  921. if c.statementCache == nil {
  922. return &pipelineBatchResults{ctx: ctx, conn: c, err: errDisabledStatementCache, closed: true}
  923. }
  924. distinctNewQueries := []*pgconn.StatementDescription{}
  925. distinctNewQueriesIdxMap := make(map[string]int)
  926. for _, bi := range b.QueuedQueries {
  927. if bi.sd == nil {
  928. sd := c.statementCache.Get(bi.SQL)
  929. if sd != nil {
  930. bi.sd = sd
  931. } else {
  932. if idx, present := distinctNewQueriesIdxMap[bi.SQL]; present {
  933. bi.sd = distinctNewQueries[idx]
  934. } else {
  935. sd = &pgconn.StatementDescription{
  936. Name: stmtcache.StatementName(bi.SQL),
  937. SQL: bi.SQL,
  938. }
  939. distinctNewQueriesIdxMap[sd.SQL] = len(distinctNewQueries)
  940. distinctNewQueries = append(distinctNewQueries, sd)
  941. bi.sd = sd
  942. }
  943. }
  944. }
  945. }
  946. return c.sendBatchExtendedWithDescription(ctx, b, distinctNewQueries, c.statementCache)
  947. }
  948. func (c *Conn) sendBatchQueryExecModeCacheDescribe(ctx context.Context, b *Batch) (pbr *pipelineBatchResults) {
  949. if c.descriptionCache == nil {
  950. return &pipelineBatchResults{ctx: ctx, conn: c, err: errDisabledDescriptionCache, closed: true}
  951. }
  952. distinctNewQueries := []*pgconn.StatementDescription{}
  953. distinctNewQueriesIdxMap := make(map[string]int)
  954. for _, bi := range b.QueuedQueries {
  955. if bi.sd == nil {
  956. sd := c.descriptionCache.Get(bi.SQL)
  957. if sd != nil {
  958. bi.sd = sd
  959. } else {
  960. if idx, present := distinctNewQueriesIdxMap[bi.SQL]; present {
  961. bi.sd = distinctNewQueries[idx]
  962. } else {
  963. sd = &pgconn.StatementDescription{
  964. SQL: bi.SQL,
  965. }
  966. distinctNewQueriesIdxMap[sd.SQL] = len(distinctNewQueries)
  967. distinctNewQueries = append(distinctNewQueries, sd)
  968. bi.sd = sd
  969. }
  970. }
  971. }
  972. }
  973. return c.sendBatchExtendedWithDescription(ctx, b, distinctNewQueries, c.descriptionCache)
  974. }
  975. func (c *Conn) sendBatchQueryExecModeDescribeExec(ctx context.Context, b *Batch) (pbr *pipelineBatchResults) {
  976. distinctNewQueries := []*pgconn.StatementDescription{}
  977. distinctNewQueriesIdxMap := make(map[string]int)
  978. for _, bi := range b.QueuedQueries {
  979. if bi.sd == nil {
  980. if idx, present := distinctNewQueriesIdxMap[bi.SQL]; present {
  981. bi.sd = distinctNewQueries[idx]
  982. } else {
  983. sd := &pgconn.StatementDescription{
  984. SQL: bi.SQL,
  985. }
  986. distinctNewQueriesIdxMap[sd.SQL] = len(distinctNewQueries)
  987. distinctNewQueries = append(distinctNewQueries, sd)
  988. bi.sd = sd
  989. }
  990. }
  991. }
  992. return c.sendBatchExtendedWithDescription(ctx, b, distinctNewQueries, nil)
  993. }
  994. func (c *Conn) sendBatchExtendedWithDescription(ctx context.Context, b *Batch, distinctNewQueries []*pgconn.StatementDescription, sdCache stmtcache.Cache) (pbr *pipelineBatchResults) {
  995. pipeline := c.pgConn.StartPipeline(ctx)
  996. defer func() {
  997. if pbr != nil && pbr.err != nil {
  998. pipeline.Close()
  999. }
  1000. }()
  1001. // Prepare any needed queries
  1002. if len(distinctNewQueries) > 0 {
  1003. err := func() (err error) {
  1004. for _, sd := range distinctNewQueries {
  1005. pipeline.SendPrepare(sd.Name, sd.SQL, nil)
  1006. }
  1007. // Store all statements we are preparing into the cache. It's fine if it overflows because HandleInvalidated will
  1008. // clean them up later.
  1009. if sdCache != nil {
  1010. for _, sd := range distinctNewQueries {
  1011. sdCache.Put(sd)
  1012. }
  1013. }
  1014. // If something goes wrong preparing the statements, we need to invalidate the cache entries we just added.
  1015. defer func() {
  1016. if err != nil && sdCache != nil {
  1017. for _, sd := range distinctNewQueries {
  1018. sdCache.Invalidate(sd.SQL)
  1019. }
  1020. }
  1021. }()
  1022. err = pipeline.Sync()
  1023. if err != nil {
  1024. return err
  1025. }
  1026. for _, sd := range distinctNewQueries {
  1027. results, err := pipeline.GetResults()
  1028. if err != nil {
  1029. return err
  1030. }
  1031. resultSD, ok := results.(*pgconn.StatementDescription)
  1032. if !ok {
  1033. return fmt.Errorf("expected statement description, got %T", results)
  1034. }
  1035. // Fill in the previously empty / pending statement descriptions.
  1036. sd.ParamOIDs = resultSD.ParamOIDs
  1037. sd.Fields = resultSD.Fields
  1038. }
  1039. results, err := pipeline.GetResults()
  1040. if err != nil {
  1041. return err
  1042. }
  1043. _, ok := results.(*pgconn.PipelineSync)
  1044. if !ok {
  1045. return fmt.Errorf("expected sync, got %T", results)
  1046. }
  1047. return nil
  1048. }()
  1049. if err != nil {
  1050. return &pipelineBatchResults{ctx: ctx, conn: c, err: err, closed: true}
  1051. }
  1052. }
  1053. // Queue the queries.
  1054. for _, bi := range b.QueuedQueries {
  1055. err := c.eqb.Build(c.typeMap, bi.sd, bi.Arguments)
  1056. if err != nil {
  1057. // we wrap the error so we the user can understand which query failed inside the batch
  1058. err = fmt.Errorf("error building query %s: %w", bi.SQL, err)
  1059. return &pipelineBatchResults{ctx: ctx, conn: c, err: err, closed: true}
  1060. }
  1061. if bi.sd.Name == "" {
  1062. pipeline.SendQueryParams(bi.sd.SQL, c.eqb.ParamValues, bi.sd.ParamOIDs, c.eqb.ParamFormats, c.eqb.ResultFormats)
  1063. } else {
  1064. pipeline.SendQueryPrepared(bi.sd.Name, c.eqb.ParamValues, c.eqb.ParamFormats, c.eqb.ResultFormats)
  1065. }
  1066. }
  1067. err := pipeline.Sync()
  1068. if err != nil {
  1069. return &pipelineBatchResults{ctx: ctx, conn: c, err: err, closed: true}
  1070. }
  1071. return &pipelineBatchResults{
  1072. ctx: ctx,
  1073. conn: c,
  1074. pipeline: pipeline,
  1075. b: b,
  1076. }
  1077. }
  1078. func (c *Conn) sanitizeForSimpleQuery(sql string, args ...any) (string, error) {
  1079. if c.pgConn.ParameterStatus("standard_conforming_strings") != "on" {
  1080. return "", errors.New("simple protocol queries must be run with standard_conforming_strings=on")
  1081. }
  1082. if c.pgConn.ParameterStatus("client_encoding") != "UTF8" {
  1083. return "", errors.New("simple protocol queries must be run with client_encoding=UTF8")
  1084. }
  1085. var err error
  1086. valueArgs := make([]any, len(args))
  1087. for i, a := range args {
  1088. valueArgs[i], err = convertSimpleArgument(c.typeMap, a)
  1089. if err != nil {
  1090. return "", err
  1091. }
  1092. }
  1093. return sanitize.SanitizeSQL(sql, valueArgs...)
  1094. }
  1095. // LoadType inspects the database for typeName and produces a pgtype.Type suitable for registration. typeName must be
  1096. // the name of a type where the underlying type(s) is already understood by pgx. It is for derived types. In particular,
  1097. // typeName must be one of the following:
  1098. // - An array type name of a type that is already registered. e.g. "_foo" when "foo" is registered.
  1099. // - A composite type name where all field types are already registered.
  1100. // - A domain type name where the base type is already registered.
  1101. // - An enum type name.
  1102. // - A range type name where the element type is already registered.
  1103. // - A multirange type name where the element type is already registered.
  1104. func (c *Conn) LoadType(ctx context.Context, typeName string) (*pgtype.Type, error) {
  1105. var oid uint32
  1106. err := c.QueryRow(ctx, "select $1::text::regtype::oid;", typeName).Scan(&oid)
  1107. if err != nil {
  1108. return nil, err
  1109. }
  1110. var typtype string
  1111. var typbasetype uint32
  1112. err = c.QueryRow(ctx, "select typtype::text, typbasetype from pg_type where oid=$1", oid).Scan(&typtype, &typbasetype)
  1113. if err != nil {
  1114. return nil, err
  1115. }
  1116. switch typtype {
  1117. case "b": // array
  1118. elementOID, err := c.getArrayElementOID(ctx, oid)
  1119. if err != nil {
  1120. return nil, err
  1121. }
  1122. dt, ok := c.TypeMap().TypeForOID(elementOID)
  1123. if !ok {
  1124. return nil, errors.New("array element OID not registered")
  1125. }
  1126. return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.ArrayCodec{ElementType: dt}}, nil
  1127. case "c": // composite
  1128. fields, err := c.getCompositeFields(ctx, oid)
  1129. if err != nil {
  1130. return nil, err
  1131. }
  1132. return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.CompositeCodec{Fields: fields}}, nil
  1133. case "d": // domain
  1134. dt, ok := c.TypeMap().TypeForOID(typbasetype)
  1135. if !ok {
  1136. return nil, errors.New("domain base type OID not registered")
  1137. }
  1138. return &pgtype.Type{Name: typeName, OID: oid, Codec: dt.Codec}, nil
  1139. case "e": // enum
  1140. return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.EnumCodec{}}, nil
  1141. case "r": // range
  1142. elementOID, err := c.getRangeElementOID(ctx, oid)
  1143. if err != nil {
  1144. return nil, err
  1145. }
  1146. dt, ok := c.TypeMap().TypeForOID(elementOID)
  1147. if !ok {
  1148. return nil, errors.New("range element OID not registered")
  1149. }
  1150. return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.RangeCodec{ElementType: dt}}, nil
  1151. case "m": // multirange
  1152. elementOID, err := c.getMultiRangeElementOID(ctx, oid)
  1153. if err != nil {
  1154. return nil, err
  1155. }
  1156. dt, ok := c.TypeMap().TypeForOID(elementOID)
  1157. if !ok {
  1158. return nil, errors.New("multirange element OID not registered")
  1159. }
  1160. return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.MultirangeCodec{ElementType: dt}}, nil
  1161. default:
  1162. return &pgtype.Type{}, errors.New("unknown typtype")
  1163. }
  1164. }
  1165. func (c *Conn) getArrayElementOID(ctx context.Context, oid uint32) (uint32, error) {
  1166. var typelem uint32
  1167. err := c.QueryRow(ctx, "select typelem from pg_type where oid=$1", oid).Scan(&typelem)
  1168. if err != nil {
  1169. return 0, err
  1170. }
  1171. return typelem, nil
  1172. }
  1173. func (c *Conn) getRangeElementOID(ctx context.Context, oid uint32) (uint32, error) {
  1174. var typelem uint32
  1175. err := c.QueryRow(ctx, "select rngsubtype from pg_range where rngtypid=$1", oid).Scan(&typelem)
  1176. if err != nil {
  1177. return 0, err
  1178. }
  1179. return typelem, nil
  1180. }
  1181. func (c *Conn) getMultiRangeElementOID(ctx context.Context, oid uint32) (uint32, error) {
  1182. var typelem uint32
  1183. err := c.QueryRow(ctx, "select rngtypid from pg_range where rngmultitypid=$1", oid).Scan(&typelem)
  1184. if err != nil {
  1185. return 0, err
  1186. }
  1187. return typelem, nil
  1188. }
  1189. func (c *Conn) getCompositeFields(ctx context.Context, oid uint32) ([]pgtype.CompositeCodecField, error) {
  1190. var typrelid uint32
  1191. err := c.QueryRow(ctx, "select typrelid from pg_type where oid=$1", oid).Scan(&typrelid)
  1192. if err != nil {
  1193. return nil, err
  1194. }
  1195. var fields []pgtype.CompositeCodecField
  1196. var fieldName string
  1197. var fieldOID uint32
  1198. rows, _ := c.Query(ctx, `select attname, atttypid
  1199. from pg_attribute
  1200. where attrelid=$1
  1201. and not attisdropped
  1202. and attnum > 0
  1203. order by attnum`,
  1204. typrelid,
  1205. )
  1206. _, err = ForEachRow(rows, []any{&fieldName, &fieldOID}, func() error {
  1207. dt, ok := c.TypeMap().TypeForOID(fieldOID)
  1208. if !ok {
  1209. return fmt.Errorf("unknown composite type field OID: %v", fieldOID)
  1210. }
  1211. fields = append(fields, pgtype.CompositeCodecField{Name: fieldName, Type: dt})
  1212. return nil
  1213. })
  1214. if err != nil {
  1215. return nil, err
  1216. }
  1217. return fields, nil
  1218. }
  1219. func (c *Conn) deallocateInvalidatedCachedStatements(ctx context.Context) error {
  1220. if txStatus := c.pgConn.TxStatus(); txStatus != 'I' && txStatus != 'T' {
  1221. return nil
  1222. }
  1223. if c.descriptionCache != nil {
  1224. c.descriptionCache.RemoveInvalidated()
  1225. }
  1226. var invalidatedStatements []*pgconn.StatementDescription
  1227. if c.statementCache != nil {
  1228. invalidatedStatements = c.statementCache.GetInvalidated()
  1229. }
  1230. if len(invalidatedStatements) == 0 {
  1231. return nil
  1232. }
  1233. pipeline := c.pgConn.StartPipeline(ctx)
  1234. defer pipeline.Close()
  1235. for _, sd := range invalidatedStatements {
  1236. pipeline.SendDeallocate(sd.Name)
  1237. }
  1238. err := pipeline.Sync()
  1239. if err != nil {
  1240. return fmt.Errorf("failed to deallocate cached statement(s): %w", err)
  1241. }
  1242. err = pipeline.Close()
  1243. if err != nil {
  1244. return fmt.Errorf("failed to deallocate cached statement(s): %w", err)
  1245. }
  1246. c.statementCache.RemoveInvalidated()
  1247. for _, sd := range invalidatedStatements {
  1248. delete(c.preparedStatements, sd.Name)
  1249. }
  1250. return nil
  1251. }