pgconn.go 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523
  1. package pgconn
  2. import (
  3. "container/list"
  4. "context"
  5. "crypto/md5"
  6. "crypto/tls"
  7. "encoding/binary"
  8. "encoding/hex"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "maps"
  13. "math"
  14. "net"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/jackc/pgx/v5/internal/iobufpool"
  20. "github.com/jackc/pgx/v5/internal/pgio"
  21. "github.com/jackc/pgx/v5/pgconn/ctxwatch"
  22. "github.com/jackc/pgx/v5/pgconn/internal/bgreader"
  23. "github.com/jackc/pgx/v5/pgproto3"
  24. )
  25. const (
  26. connStatusUninitialized = iota
  27. connStatusConnecting
  28. connStatusClosed
  29. connStatusIdle
  30. connStatusBusy
  31. )
  32. // Notice represents a notice response message reported by the PostgreSQL server. Be aware that this is distinct from
  33. // LISTEN/NOTIFY notification.
  34. type Notice PgError
  35. // Notification is a message received from the PostgreSQL LISTEN/NOTIFY system
  36. type Notification struct {
  37. PID uint32 // backend pid that sent the notification
  38. Channel string // channel from which notification was received
  39. Payload string
  40. }
  41. // DialFunc is a function that can be used to connect to a PostgreSQL server.
  42. type DialFunc func(ctx context.Context, network, addr string) (net.Conn, error)
  43. // LookupFunc is a function that can be used to lookup IPs addrs from host. Optionally an ip:port combination can be
  44. // returned in order to override the connection string's port.
  45. type LookupFunc func(ctx context.Context, host string) (addrs []string, err error)
  46. // BuildFrontendFunc is a function that can be used to create Frontend implementation for connection.
  47. type BuildFrontendFunc func(r io.Reader, w io.Writer) *pgproto3.Frontend
  48. // PgErrorHandler is a function that handles errors returned from Postgres. This function must return true to keep
  49. // the connection open. Returning false will cause the connection to be closed immediately. You should return
  50. // false on any FATAL-severity errors. This will not receive network errors. The *PgConn is provided so the handler is
  51. // aware of the origin of the error, but it must not invoke any query method.
  52. type PgErrorHandler func(*PgConn, *PgError) bool
  53. // NoticeHandler is a function that can handle notices received from the PostgreSQL server. Notices can be received at
  54. // any time, usually during handling of a query response. The *PgConn is provided so the handler is aware of the origin
  55. // of the notice, but it must not invoke any query method. Be aware that this is distinct from LISTEN/NOTIFY
  56. // notification.
  57. type NoticeHandler func(*PgConn, *Notice)
  58. // NotificationHandler is a function that can handle notifications received from the PostgreSQL server. Notifications
  59. // can be received at any time, usually during handling of a query response. The *PgConn is provided so the handler is
  60. // aware of the origin of the notice, but it must not invoke any query method. Be aware that this is distinct from a
  61. // notice event.
  62. type NotificationHandler func(*PgConn, *Notification)
  63. // PgConn is a low-level PostgreSQL connection handle. It is not safe for concurrent usage.
  64. type PgConn struct {
  65. conn net.Conn
  66. pid uint32 // backend pid
  67. secretKey uint32 // key to use to send a cancel query message to the server
  68. parameterStatuses map[string]string // parameters that have been reported by the server
  69. txStatus byte
  70. frontend *pgproto3.Frontend
  71. bgReader *bgreader.BGReader
  72. slowWriteTimer *time.Timer
  73. bgReaderStarted chan struct{}
  74. customData map[string]any
  75. config *Config
  76. status byte // One of connStatus* constants
  77. bufferingReceive bool
  78. bufferingReceiveMux sync.Mutex
  79. bufferingReceiveMsg pgproto3.BackendMessage
  80. bufferingReceiveErr error
  81. peekedMsg pgproto3.BackendMessage
  82. // Reusable / preallocated resources
  83. resultReader ResultReader
  84. multiResultReader MultiResultReader
  85. pipeline Pipeline
  86. contextWatcher *ctxwatch.ContextWatcher
  87. fieldDescriptions [16]FieldDescription
  88. cleanupDone chan struct{}
  89. }
  90. // Connect establishes a connection to a PostgreSQL server using the environment and connString (in URL or keyword/value
  91. // format) to provide configuration. See documentation for [ParseConfig] for details. ctx can be used to cancel a
  92. // connect attempt.
  93. func Connect(ctx context.Context, connString string) (*PgConn, error) {
  94. config, err := ParseConfig(connString)
  95. if err != nil {
  96. return nil, err
  97. }
  98. return ConnectConfig(ctx, config)
  99. }
  100. // Connect establishes a connection to a PostgreSQL server using the environment and connString (in URL or keyword/value
  101. // format) and ParseConfigOptions to provide additional configuration. See documentation for [ParseConfig] for details.
  102. // ctx can be used to cancel a connect attempt.
  103. func ConnectWithOptions(ctx context.Context, connString string, parseConfigOptions ParseConfigOptions) (*PgConn, error) {
  104. config, err := ParseConfigWithOptions(connString, parseConfigOptions)
  105. if err != nil {
  106. return nil, err
  107. }
  108. return ConnectConfig(ctx, config)
  109. }
  110. // Connect establishes a connection to a PostgreSQL server using config. config must have been constructed with
  111. // [ParseConfig]. ctx can be used to cancel a connect attempt.
  112. //
  113. // If config.Fallbacks are present they will sequentially be tried in case of error establishing network connection. An
  114. // authentication error will terminate the chain of attempts (like libpq:
  115. // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS) and be returned as the error.
  116. func ConnectConfig(ctx context.Context, config *Config) (*PgConn, error) {
  117. // Default values are set in ParseConfig. Enforce initial creation by ParseConfig rather than setting defaults from
  118. // zero values.
  119. if !config.createdByParseConfig {
  120. panic("config must be created by ParseConfig")
  121. }
  122. var allErrors []error
  123. connectConfigs, errs := buildConnectOneConfigs(ctx, config)
  124. if len(errs) > 0 {
  125. allErrors = append(allErrors, errs...)
  126. }
  127. if len(connectConfigs) == 0 {
  128. return nil, &ConnectError{Config: config, err: fmt.Errorf("hostname resolving error: %w", errors.Join(allErrors...))}
  129. }
  130. pgConn, errs := connectPreferred(ctx, config, connectConfigs)
  131. if len(errs) > 0 {
  132. allErrors = append(allErrors, errs...)
  133. return nil, &ConnectError{Config: config, err: errors.Join(allErrors...)}
  134. }
  135. if config.AfterConnect != nil {
  136. err := config.AfterConnect(ctx, pgConn)
  137. if err != nil {
  138. pgConn.conn.Close()
  139. return nil, &ConnectError{Config: config, err: fmt.Errorf("AfterConnect error: %w", err)}
  140. }
  141. }
  142. return pgConn, nil
  143. }
  144. // buildConnectOneConfigs resolves hostnames and builds a list of connectOneConfigs to try connecting to. It returns a
  145. // slice of successfully resolved connectOneConfigs and a slice of errors. It is possible for both slices to contain
  146. // values if some hosts were successfully resolved and others were not.
  147. func buildConnectOneConfigs(ctx context.Context, config *Config) ([]*connectOneConfig, []error) {
  148. // Simplify usage by treating primary config and fallbacks the same.
  149. fallbackConfigs := []*FallbackConfig{
  150. {
  151. Host: config.Host,
  152. Port: config.Port,
  153. TLSConfig: config.TLSConfig,
  154. },
  155. }
  156. fallbackConfigs = append(fallbackConfigs, config.Fallbacks...)
  157. var configs []*connectOneConfig
  158. var allErrors []error
  159. for _, fb := range fallbackConfigs {
  160. // skip resolve for unix sockets
  161. if isAbsolutePath(fb.Host) {
  162. network, address := NetworkAddress(fb.Host, fb.Port)
  163. configs = append(configs, &connectOneConfig{
  164. network: network,
  165. address: address,
  166. originalHostname: fb.Host,
  167. tlsConfig: fb.TLSConfig,
  168. })
  169. continue
  170. }
  171. ips, err := config.LookupFunc(ctx, fb.Host)
  172. if err != nil {
  173. allErrors = append(allErrors, err)
  174. continue
  175. }
  176. for _, ip := range ips {
  177. splitIP, splitPort, err := net.SplitHostPort(ip)
  178. if err == nil {
  179. port, err := strconv.ParseUint(splitPort, 10, 16)
  180. if err != nil {
  181. return nil, []error{fmt.Errorf("error parsing port (%s) from lookup: %w", splitPort, err)}
  182. }
  183. network, address := NetworkAddress(splitIP, uint16(port))
  184. configs = append(configs, &connectOneConfig{
  185. network: network,
  186. address: address,
  187. originalHostname: fb.Host,
  188. tlsConfig: fb.TLSConfig,
  189. })
  190. } else {
  191. network, address := NetworkAddress(ip, fb.Port)
  192. configs = append(configs, &connectOneConfig{
  193. network: network,
  194. address: address,
  195. originalHostname: fb.Host,
  196. tlsConfig: fb.TLSConfig,
  197. })
  198. }
  199. }
  200. }
  201. return configs, allErrors
  202. }
  203. // connectPreferred attempts to connect to the preferred host from connectOneConfigs. The connections are attempted in
  204. // order. If a connection is successful it is returned. If no connection is successful then all errors are returned. If
  205. // a connection attempt returns a [NotPreferredError], then that host will be used if no other hosts are successful.
  206. func connectPreferred(ctx context.Context, config *Config, connectOneConfigs []*connectOneConfig) (*PgConn, []error) {
  207. octx := ctx
  208. var allErrors []error
  209. var fallbackConnectOneConfig *connectOneConfig
  210. for i, c := range connectOneConfigs {
  211. // ConnectTimeout restricts the whole connection process.
  212. if config.ConnectTimeout != 0 {
  213. // create new context first time or when previous host was different
  214. if i == 0 || (connectOneConfigs[i].address != connectOneConfigs[i-1].address) {
  215. var cancel context.CancelFunc
  216. ctx, cancel = context.WithTimeout(octx, config.ConnectTimeout)
  217. defer cancel()
  218. }
  219. } else {
  220. ctx = octx
  221. }
  222. pgConn, err := connectOne(ctx, config, c, false)
  223. if pgConn != nil {
  224. return pgConn, nil
  225. }
  226. allErrors = append(allErrors, err)
  227. var pgErr *PgError
  228. if errors.As(err, &pgErr) {
  229. // pgx will try next host even if libpq does not in certain cases (see #2246)
  230. // consider change for the next major version
  231. const ERRCODE_INVALID_PASSWORD = "28P01"
  232. const ERRCODE_INVALID_CATALOG_NAME = "3D000" // db does not exist
  233. const ERRCODE_INSUFFICIENT_PRIVILEGE = "42501" // missing connect privilege
  234. // auth failed due to invalid password, db does not exist or user has no permission
  235. if pgErr.Code == ERRCODE_INVALID_PASSWORD ||
  236. pgErr.Code == ERRCODE_INVALID_CATALOG_NAME ||
  237. pgErr.Code == ERRCODE_INSUFFICIENT_PRIVILEGE {
  238. return nil, allErrors
  239. }
  240. }
  241. var npErr *NotPreferredError
  242. if errors.As(err, &npErr) {
  243. fallbackConnectOneConfig = c
  244. }
  245. }
  246. if fallbackConnectOneConfig != nil {
  247. pgConn, err := connectOne(ctx, config, fallbackConnectOneConfig, true)
  248. if err == nil {
  249. return pgConn, nil
  250. }
  251. allErrors = append(allErrors, err)
  252. }
  253. return nil, allErrors
  254. }
  255. // connectOne makes one connection attempt to a single host.
  256. func connectOne(ctx context.Context, config *Config, connectConfig *connectOneConfig,
  257. ignoreNotPreferredErr bool,
  258. ) (*PgConn, error) {
  259. pgConn := new(PgConn)
  260. pgConn.config = config
  261. pgConn.cleanupDone = make(chan struct{})
  262. pgConn.customData = make(map[string]any)
  263. var err error
  264. newPerDialConnectError := func(msg string, err error) *perDialConnectError {
  265. err = normalizeTimeoutError(ctx, err)
  266. e := &perDialConnectError{address: connectConfig.address, originalHostname: connectConfig.originalHostname, err: fmt.Errorf("%s: %w", msg, err)}
  267. return e
  268. }
  269. pgConn.conn, err = config.DialFunc(ctx, connectConfig.network, connectConfig.address)
  270. if err != nil {
  271. return nil, newPerDialConnectError("dial error", err)
  272. }
  273. if connectConfig.tlsConfig != nil {
  274. pgConn.contextWatcher = ctxwatch.NewContextWatcher(&DeadlineContextWatcherHandler{Conn: pgConn.conn})
  275. pgConn.contextWatcher.Watch(ctx)
  276. var (
  277. tlsConn net.Conn
  278. err error
  279. )
  280. if config.SSLNegotiation == "direct" {
  281. tlsConn = tls.Client(pgConn.conn, connectConfig.tlsConfig)
  282. } else {
  283. tlsConn, err = startTLS(pgConn.conn, connectConfig.tlsConfig)
  284. }
  285. pgConn.contextWatcher.Unwatch() // Always unwatch `netConn` after TLS.
  286. if err != nil {
  287. pgConn.conn.Close()
  288. return nil, newPerDialConnectError("tls error", err)
  289. }
  290. pgConn.conn = tlsConn
  291. }
  292. if config.AfterNetConnect != nil {
  293. pgConn.conn, err = config.AfterNetConnect(ctx, config, pgConn.conn)
  294. if err != nil {
  295. pgConn.conn.Close()
  296. return nil, newPerDialConnectError("AfterNetConnect failed", err)
  297. }
  298. }
  299. pgConn.contextWatcher = ctxwatch.NewContextWatcher(config.BuildContextWatcherHandler(pgConn))
  300. pgConn.contextWatcher.Watch(ctx)
  301. defer pgConn.contextWatcher.Unwatch()
  302. pgConn.parameterStatuses = make(map[string]string)
  303. pgConn.status = connStatusConnecting
  304. pgConn.bgReader = bgreader.New(pgConn.conn)
  305. pgConn.slowWriteTimer = time.AfterFunc(time.Duration(math.MaxInt64),
  306. func() {
  307. pgConn.bgReader.Start()
  308. pgConn.bgReaderStarted <- struct{}{}
  309. },
  310. )
  311. pgConn.slowWriteTimer.Stop()
  312. pgConn.bgReaderStarted = make(chan struct{})
  313. pgConn.frontend = config.BuildFrontend(pgConn.bgReader, pgConn.conn)
  314. startupMsg := pgproto3.StartupMessage{
  315. ProtocolVersion: pgproto3.ProtocolVersionNumber,
  316. Parameters: make(map[string]string),
  317. }
  318. // Copy default run-time params
  319. maps.Copy(startupMsg.Parameters, config.RuntimeParams)
  320. startupMsg.Parameters["user"] = config.User
  321. if config.Database != "" {
  322. startupMsg.Parameters["database"] = config.Database
  323. }
  324. pgConn.frontend.Send(&startupMsg)
  325. if err := pgConn.flushWithPotentialWriteReadDeadlock(); err != nil {
  326. pgConn.conn.Close()
  327. return nil, newPerDialConnectError("failed to write startup message", err)
  328. }
  329. for {
  330. msg, err := pgConn.receiveMessage()
  331. if err != nil {
  332. pgConn.conn.Close()
  333. if err, ok := err.(*PgError); ok {
  334. return nil, newPerDialConnectError("server error", err)
  335. }
  336. return nil, newPerDialConnectError("failed to receive message", err)
  337. }
  338. switch msg := msg.(type) {
  339. case *pgproto3.BackendKeyData:
  340. pgConn.pid = msg.ProcessID
  341. pgConn.secretKey = msg.SecretKey
  342. case *pgproto3.AuthenticationOk:
  343. case *pgproto3.AuthenticationCleartextPassword:
  344. err = pgConn.txPasswordMessage(pgConn.config.Password)
  345. if err != nil {
  346. pgConn.conn.Close()
  347. return nil, newPerDialConnectError("failed to write password message", err)
  348. }
  349. case *pgproto3.AuthenticationMD5Password:
  350. digestedPassword := "md5" + hexMD5(hexMD5(pgConn.config.Password+pgConn.config.User)+string(msg.Salt[:]))
  351. err = pgConn.txPasswordMessage(digestedPassword)
  352. if err != nil {
  353. pgConn.conn.Close()
  354. return nil, newPerDialConnectError("failed to write password message", err)
  355. }
  356. case *pgproto3.AuthenticationSASL:
  357. err = pgConn.scramAuth(msg.AuthMechanisms)
  358. if err != nil {
  359. pgConn.conn.Close()
  360. return nil, newPerDialConnectError("failed SASL auth", err)
  361. }
  362. case *pgproto3.AuthenticationGSS:
  363. err = pgConn.gssAuth()
  364. if err != nil {
  365. pgConn.conn.Close()
  366. return nil, newPerDialConnectError("failed GSS auth", err)
  367. }
  368. case *pgproto3.ReadyForQuery:
  369. pgConn.status = connStatusIdle
  370. if config.ValidateConnect != nil {
  371. // ValidateConnect may execute commands that cause the context to be watched again. Unwatch first to avoid
  372. // the watch already in progress panic. This is that last thing done by this method so there is no need to
  373. // restart the watch after ValidateConnect returns.
  374. //
  375. // See https://github.com/jackc/pgconn/issues/40.
  376. pgConn.contextWatcher.Unwatch()
  377. err := config.ValidateConnect(ctx, pgConn)
  378. if err != nil {
  379. if _, ok := err.(*NotPreferredError); ignoreNotPreferredErr && ok {
  380. return pgConn, nil
  381. }
  382. pgConn.conn.Close()
  383. return nil, newPerDialConnectError("ValidateConnect failed", err)
  384. }
  385. }
  386. return pgConn, nil
  387. case *pgproto3.ParameterStatus, *pgproto3.NoticeResponse:
  388. // handled by ReceiveMessage
  389. case *pgproto3.ErrorResponse:
  390. pgConn.conn.Close()
  391. return nil, newPerDialConnectError("server error", ErrorResponseToPgError(msg))
  392. default:
  393. pgConn.conn.Close()
  394. return nil, newPerDialConnectError("received unexpected message", err)
  395. }
  396. }
  397. }
  398. func startTLS(conn net.Conn, tlsConfig *tls.Config) (net.Conn, error) {
  399. err := binary.Write(conn, binary.BigEndian, []int32{8, 80877103})
  400. if err != nil {
  401. return nil, err
  402. }
  403. response := make([]byte, 1)
  404. if _, err = io.ReadFull(conn, response); err != nil {
  405. return nil, err
  406. }
  407. if response[0] != 'S' {
  408. return nil, errors.New("server refused TLS connection")
  409. }
  410. return tls.Client(conn, tlsConfig), nil
  411. }
  412. func (pgConn *PgConn) txPasswordMessage(password string) (err error) {
  413. pgConn.frontend.Send(&pgproto3.PasswordMessage{Password: password})
  414. return pgConn.flushWithPotentialWriteReadDeadlock()
  415. }
  416. func hexMD5(s string) string {
  417. hash := md5.New()
  418. io.WriteString(hash, s)
  419. return hex.EncodeToString(hash.Sum(nil))
  420. }
  421. func (pgConn *PgConn) signalMessage() chan struct{} {
  422. if pgConn.bufferingReceive {
  423. panic("BUG: signalMessage when already in progress")
  424. }
  425. pgConn.bufferingReceive = true
  426. pgConn.bufferingReceiveMux.Lock()
  427. ch := make(chan struct{})
  428. go func() {
  429. pgConn.bufferingReceiveMsg, pgConn.bufferingReceiveErr = pgConn.frontend.Receive()
  430. pgConn.bufferingReceiveMux.Unlock()
  431. close(ch)
  432. }()
  433. return ch
  434. }
  435. // ReceiveMessage receives one wire protocol message from the PostgreSQL server. It must only be used when the
  436. // connection is not busy. e.g. It is an error to call ReceiveMessage while reading the result of a query. The messages
  437. // are still handled by the core pgconn message handling system so receiving a NotificationResponse will still trigger
  438. // the OnNotification callback.
  439. //
  440. // This is a very low level method that requires deep understanding of the PostgreSQL wire protocol to use correctly.
  441. // See https://www.postgresql.org/docs/current/protocol.html.
  442. func (pgConn *PgConn) ReceiveMessage(ctx context.Context) (pgproto3.BackendMessage, error) {
  443. if err := pgConn.lock(); err != nil {
  444. return nil, err
  445. }
  446. defer pgConn.unlock()
  447. if ctx != context.Background() {
  448. select {
  449. case <-ctx.Done():
  450. return nil, newContextAlreadyDoneError(ctx)
  451. default:
  452. }
  453. pgConn.contextWatcher.Watch(ctx)
  454. defer pgConn.contextWatcher.Unwatch()
  455. }
  456. msg, err := pgConn.receiveMessage()
  457. if err != nil {
  458. err = &pgconnError{
  459. msg: "receive message failed",
  460. err: normalizeTimeoutError(ctx, err),
  461. safeToRetry: true,
  462. }
  463. }
  464. return msg, err
  465. }
  466. // peekMessage peeks at the next message without setting up context cancellation.
  467. func (pgConn *PgConn) peekMessage() (pgproto3.BackendMessage, error) {
  468. if pgConn.peekedMsg != nil {
  469. return pgConn.peekedMsg, nil
  470. }
  471. var msg pgproto3.BackendMessage
  472. var err error
  473. if pgConn.bufferingReceive {
  474. pgConn.bufferingReceiveMux.Lock()
  475. msg = pgConn.bufferingReceiveMsg
  476. err = pgConn.bufferingReceiveErr
  477. pgConn.bufferingReceiveMux.Unlock()
  478. pgConn.bufferingReceive = false
  479. // If a timeout error happened in the background try the read again.
  480. var netErr net.Error
  481. if errors.As(err, &netErr) && netErr.Timeout() {
  482. msg, err = pgConn.frontend.Receive()
  483. }
  484. } else {
  485. msg, err = pgConn.frontend.Receive()
  486. }
  487. if err != nil {
  488. // Close on anything other than timeout error - everything else is fatal
  489. var netErr net.Error
  490. isNetErr := errors.As(err, &netErr)
  491. if !(isNetErr && netErr.Timeout()) {
  492. pgConn.asyncClose()
  493. }
  494. return nil, err
  495. }
  496. pgConn.peekedMsg = msg
  497. return msg, nil
  498. }
  499. // receiveMessage receives a message without setting up context cancellation
  500. func (pgConn *PgConn) receiveMessage() (pgproto3.BackendMessage, error) {
  501. msg, err := pgConn.peekMessage()
  502. if err != nil {
  503. return nil, err
  504. }
  505. pgConn.peekedMsg = nil
  506. switch msg := msg.(type) {
  507. case *pgproto3.ReadyForQuery:
  508. pgConn.txStatus = msg.TxStatus
  509. case *pgproto3.ParameterStatus:
  510. pgConn.parameterStatuses[msg.Name] = msg.Value
  511. case *pgproto3.ErrorResponse:
  512. err := ErrorResponseToPgError(msg)
  513. if pgConn.config.OnPgError != nil && !pgConn.config.OnPgError(pgConn, err) {
  514. pgConn.status = connStatusClosed
  515. pgConn.conn.Close() // Ignore error as the connection is already broken and there is already an error to return.
  516. close(pgConn.cleanupDone)
  517. return nil, err
  518. }
  519. case *pgproto3.NoticeResponse:
  520. if pgConn.config.OnNotice != nil {
  521. pgConn.config.OnNotice(pgConn, noticeResponseToNotice(msg))
  522. }
  523. case *pgproto3.NotificationResponse:
  524. if pgConn.config.OnNotification != nil {
  525. pgConn.config.OnNotification(pgConn, &Notification{PID: msg.PID, Channel: msg.Channel, Payload: msg.Payload})
  526. }
  527. }
  528. return msg, nil
  529. }
  530. // Conn returns the underlying net.Conn. This rarely necessary. If the connection will be directly used for reading or
  531. // writing then SyncConn should usually be called before Conn.
  532. func (pgConn *PgConn) Conn() net.Conn {
  533. return pgConn.conn
  534. }
  535. // PID returns the backend PID.
  536. func (pgConn *PgConn) PID() uint32 {
  537. return pgConn.pid
  538. }
  539. // TxStatus returns the current TxStatus as reported by the server in the ReadyForQuery message.
  540. //
  541. // Possible return values:
  542. //
  543. // 'I' - idle / not in transaction
  544. // 'T' - in a transaction
  545. // 'E' - in a failed transaction
  546. //
  547. // See https://www.postgresql.org/docs/current/protocol-message-formats.html.
  548. func (pgConn *PgConn) TxStatus() byte {
  549. return pgConn.txStatus
  550. }
  551. // SecretKey returns the backend secret key used to send a cancel query message to the server.
  552. func (pgConn *PgConn) SecretKey() uint32 {
  553. return pgConn.secretKey
  554. }
  555. // Frontend returns the underlying *pgproto3.Frontend. This rarely necessary.
  556. func (pgConn *PgConn) Frontend() *pgproto3.Frontend {
  557. return pgConn.frontend
  558. }
  559. // Close closes a connection. It is safe to call Close on an already closed connection. Close attempts a clean close by
  560. // sending the exit message to PostgreSQL. However, this could block so ctx is available to limit the time to wait. The
  561. // underlying net.Conn.Close() will always be called regardless of any other errors.
  562. func (pgConn *PgConn) Close(ctx context.Context) error {
  563. if pgConn.status == connStatusClosed {
  564. return nil
  565. }
  566. pgConn.status = connStatusClosed
  567. defer close(pgConn.cleanupDone)
  568. defer pgConn.conn.Close()
  569. if ctx != context.Background() {
  570. // Close may be called while a cancellable query is in progress. This will most often be triggered by panic when
  571. // a defer closes the connection (possibly indirectly via a transaction or a connection pool). Unwatch to end any
  572. // previous watch. It is safe to Unwatch regardless of whether a watch is already is progress.
  573. //
  574. // See https://github.com/jackc/pgconn/issues/29
  575. pgConn.contextWatcher.Unwatch()
  576. pgConn.contextWatcher.Watch(ctx)
  577. defer pgConn.contextWatcher.Unwatch()
  578. }
  579. // Ignore any errors sending Terminate message and waiting for server to close connection.
  580. // This mimics the behavior of libpq PQfinish. It calls closePGconn which calls sendTerminateConn which purposefully
  581. // ignores errors.
  582. //
  583. // See https://github.com/jackc/pgx/issues/637
  584. pgConn.frontend.Send(&pgproto3.Terminate{})
  585. pgConn.flushWithPotentialWriteReadDeadlock()
  586. return pgConn.conn.Close()
  587. }
  588. // asyncClose marks the connection as closed and asynchronously sends a cancel query message and closes the underlying
  589. // connection.
  590. func (pgConn *PgConn) asyncClose() {
  591. if pgConn.status == connStatusClosed {
  592. return
  593. }
  594. pgConn.status = connStatusClosed
  595. go func() {
  596. defer close(pgConn.cleanupDone)
  597. defer pgConn.conn.Close()
  598. deadline := time.Now().Add(time.Second * 15)
  599. ctx, cancel := context.WithDeadline(context.Background(), deadline)
  600. defer cancel()
  601. pgConn.CancelRequest(ctx)
  602. pgConn.conn.SetDeadline(deadline)
  603. pgConn.frontend.Send(&pgproto3.Terminate{})
  604. pgConn.flushWithPotentialWriteReadDeadlock()
  605. }()
  606. }
  607. // CleanupDone returns a channel that will be closed after all underlying resources have been cleaned up. A closed
  608. // connection is no longer usable, but underlying resources, in particular the net.Conn, may not have finished closing
  609. // yet. This is because certain errors such as a context cancellation require that the interrupted function call return
  610. // immediately, but the error may also cause the connection to be closed. In these cases the underlying resources are
  611. // closed asynchronously.
  612. //
  613. // This is only likely to be useful to connection pools. It gives them a way avoid establishing a new connection while
  614. // an old connection is still being cleaned up and thereby exceeding the maximum pool size.
  615. func (pgConn *PgConn) CleanupDone() chan (struct{}) {
  616. return pgConn.cleanupDone
  617. }
  618. // IsClosed reports if the connection has been closed.
  619. //
  620. // CleanupDone() can be used to determine if all cleanup has been completed.
  621. func (pgConn *PgConn) IsClosed() bool {
  622. return pgConn.status < connStatusIdle
  623. }
  624. // IsBusy reports if the connection is busy.
  625. func (pgConn *PgConn) IsBusy() bool {
  626. return pgConn.status == connStatusBusy
  627. }
  628. // lock locks the connection.
  629. func (pgConn *PgConn) lock() error {
  630. switch pgConn.status {
  631. case connStatusBusy:
  632. return &connLockError{status: "conn busy"} // This only should be possible in case of an application bug.
  633. case connStatusClosed:
  634. return &connLockError{status: "conn closed"}
  635. case connStatusUninitialized:
  636. return &connLockError{status: "conn uninitialized"}
  637. }
  638. pgConn.status = connStatusBusy
  639. return nil
  640. }
  641. func (pgConn *PgConn) unlock() {
  642. switch pgConn.status {
  643. case connStatusBusy:
  644. pgConn.status = connStatusIdle
  645. case connStatusClosed:
  646. default:
  647. panic("BUG: cannot unlock unlocked connection") // This should only be possible if there is a bug in this package.
  648. }
  649. }
  650. // ParameterStatus returns the value of a parameter reported by the server (e.g.
  651. // server_version). Returns an empty string for unknown parameters.
  652. func (pgConn *PgConn) ParameterStatus(key string) string {
  653. return pgConn.parameterStatuses[key]
  654. }
  655. // CommandTag is the status text returned by PostgreSQL for a query.
  656. type CommandTag struct {
  657. s string
  658. }
  659. // NewCommandTag makes a CommandTag from s.
  660. func NewCommandTag(s string) CommandTag {
  661. return CommandTag{s: s}
  662. }
  663. // RowsAffected returns the number of rows affected. If the CommandTag was not
  664. // for a row affecting command (e.g. "CREATE TABLE") then it returns 0.
  665. func (ct CommandTag) RowsAffected() int64 {
  666. // Find last non-digit
  667. idx := -1
  668. for i := len(ct.s) - 1; i >= 0; i-- {
  669. if ct.s[i] >= '0' && ct.s[i] <= '9' {
  670. idx = i
  671. } else {
  672. break
  673. }
  674. }
  675. if idx == -1 {
  676. return 0
  677. }
  678. var n int64
  679. for _, b := range ct.s[idx:] {
  680. n = n*10 + int64(b-'0')
  681. }
  682. return n
  683. }
  684. func (ct CommandTag) String() string {
  685. return ct.s
  686. }
  687. // Insert is true if the command tag starts with "INSERT".
  688. func (ct CommandTag) Insert() bool {
  689. return strings.HasPrefix(ct.s, "INSERT")
  690. }
  691. // Update is true if the command tag starts with "UPDATE".
  692. func (ct CommandTag) Update() bool {
  693. return strings.HasPrefix(ct.s, "UPDATE")
  694. }
  695. // Delete is true if the command tag starts with "DELETE".
  696. func (ct CommandTag) Delete() bool {
  697. return strings.HasPrefix(ct.s, "DELETE")
  698. }
  699. // Select is true if the command tag starts with "SELECT".
  700. func (ct CommandTag) Select() bool {
  701. return strings.HasPrefix(ct.s, "SELECT")
  702. }
  703. type FieldDescription struct {
  704. Name string
  705. TableOID uint32
  706. TableAttributeNumber uint16
  707. DataTypeOID uint32
  708. DataTypeSize int16
  709. TypeModifier int32
  710. Format int16
  711. }
  712. func (pgConn *PgConn) convertRowDescription(dst []FieldDescription, rd *pgproto3.RowDescription) []FieldDescription {
  713. if cap(dst) >= len(rd.Fields) {
  714. dst = dst[:len(rd.Fields):len(rd.Fields)]
  715. } else {
  716. dst = make([]FieldDescription, len(rd.Fields))
  717. }
  718. for i := range rd.Fields {
  719. dst[i].Name = string(rd.Fields[i].Name)
  720. dst[i].TableOID = rd.Fields[i].TableOID
  721. dst[i].TableAttributeNumber = rd.Fields[i].TableAttributeNumber
  722. dst[i].DataTypeOID = rd.Fields[i].DataTypeOID
  723. dst[i].DataTypeSize = rd.Fields[i].DataTypeSize
  724. dst[i].TypeModifier = rd.Fields[i].TypeModifier
  725. dst[i].Format = rd.Fields[i].Format
  726. }
  727. return dst
  728. }
  729. type StatementDescription struct {
  730. Name string
  731. SQL string
  732. ParamOIDs []uint32
  733. Fields []FieldDescription
  734. }
  735. // Prepare creates a prepared statement. If the name is empty, the anonymous prepared statement will be used. This
  736. // allows Prepare to also to describe statements without creating a server-side prepared statement.
  737. //
  738. // Prepare does not send a PREPARE statement to the server. It uses the PostgreSQL Parse and Describe protocol messages
  739. // directly.
  740. //
  741. // In extremely rare cases, Prepare may fail after the Parse is successful, but before the Describe is complete. In this
  742. // case, the returned error will be an error where errors.As with a *PrepareError succeeds and the *PrepareError has
  743. // ParseComplete set to true.
  744. func (pgConn *PgConn) Prepare(ctx context.Context, name, sql string, paramOIDs []uint32) (*StatementDescription, error) {
  745. if err := pgConn.lock(); err != nil {
  746. return nil, err
  747. }
  748. defer pgConn.unlock()
  749. if ctx != context.Background() {
  750. select {
  751. case <-ctx.Done():
  752. return nil, newContextAlreadyDoneError(ctx)
  753. default:
  754. }
  755. pgConn.contextWatcher.Watch(ctx)
  756. defer pgConn.contextWatcher.Unwatch()
  757. }
  758. pgConn.frontend.SendParse(&pgproto3.Parse{Name: name, Query: sql, ParameterOIDs: paramOIDs})
  759. pgConn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'S', Name: name})
  760. pgConn.frontend.SendSync(&pgproto3.Sync{})
  761. err := pgConn.flushWithPotentialWriteReadDeadlock()
  762. if err != nil {
  763. pgConn.asyncClose()
  764. return nil, err
  765. }
  766. psd := &StatementDescription{Name: name, SQL: sql}
  767. var ParseComplete bool
  768. var pgErr *PgError
  769. readloop:
  770. for {
  771. msg, err := pgConn.receiveMessage()
  772. if err != nil {
  773. pgConn.asyncClose()
  774. return nil, normalizeTimeoutError(ctx, err)
  775. }
  776. switch msg := msg.(type) {
  777. case *pgproto3.ParseComplete:
  778. ParseComplete = true
  779. case *pgproto3.ParameterDescription:
  780. psd.ParamOIDs = make([]uint32, len(msg.ParameterOIDs))
  781. copy(psd.ParamOIDs, msg.ParameterOIDs)
  782. case *pgproto3.RowDescription:
  783. psd.Fields = pgConn.convertRowDescription(nil, msg)
  784. case *pgproto3.ErrorResponse:
  785. pgErr = ErrorResponseToPgError(msg)
  786. case *pgproto3.ReadyForQuery:
  787. break readloop
  788. }
  789. }
  790. if pgErr != nil {
  791. return nil, &PrepareError{err: pgErr, ParseComplete: ParseComplete}
  792. }
  793. return psd, nil
  794. }
  795. // Deallocate deallocates a prepared statement.
  796. //
  797. // Deallocate does not send a DEALLOCATE statement to the server. It uses the PostgreSQL Close protocol message
  798. // directly. This has slightly different behavior than executing DEALLOCATE statement.
  799. // - Deallocate can succeed in an aborted transaction.
  800. // - Deallocating a non-existent prepared statement is not an error.
  801. func (pgConn *PgConn) Deallocate(ctx context.Context, name string) error {
  802. if err := pgConn.lock(); err != nil {
  803. return err
  804. }
  805. defer pgConn.unlock()
  806. if ctx != context.Background() {
  807. select {
  808. case <-ctx.Done():
  809. return newContextAlreadyDoneError(ctx)
  810. default:
  811. }
  812. pgConn.contextWatcher.Watch(ctx)
  813. defer pgConn.contextWatcher.Unwatch()
  814. }
  815. pgConn.frontend.SendClose(&pgproto3.Close{ObjectType: 'S', Name: name})
  816. pgConn.frontend.SendSync(&pgproto3.Sync{})
  817. err := pgConn.flushWithPotentialWriteReadDeadlock()
  818. if err != nil {
  819. pgConn.asyncClose()
  820. return err
  821. }
  822. for {
  823. msg, err := pgConn.receiveMessage()
  824. if err != nil {
  825. pgConn.asyncClose()
  826. return normalizeTimeoutError(ctx, err)
  827. }
  828. switch msg := msg.(type) {
  829. case *pgproto3.ErrorResponse:
  830. return ErrorResponseToPgError(msg)
  831. case *pgproto3.ReadyForQuery:
  832. return nil
  833. }
  834. }
  835. }
  836. // ErrorResponseToPgError converts a wire protocol error message to a *PgError.
  837. func ErrorResponseToPgError(msg *pgproto3.ErrorResponse) *PgError {
  838. return &PgError{
  839. Severity: msg.Severity,
  840. SeverityUnlocalized: msg.SeverityUnlocalized,
  841. Code: string(msg.Code),
  842. Message: string(msg.Message),
  843. Detail: string(msg.Detail),
  844. Hint: msg.Hint,
  845. Position: msg.Position,
  846. InternalPosition: msg.InternalPosition,
  847. InternalQuery: string(msg.InternalQuery),
  848. Where: string(msg.Where),
  849. SchemaName: string(msg.SchemaName),
  850. TableName: string(msg.TableName),
  851. ColumnName: string(msg.ColumnName),
  852. DataTypeName: string(msg.DataTypeName),
  853. ConstraintName: msg.ConstraintName,
  854. File: string(msg.File),
  855. Line: msg.Line,
  856. Routine: string(msg.Routine),
  857. }
  858. }
  859. func noticeResponseToNotice(msg *pgproto3.NoticeResponse) *Notice {
  860. pgerr := ErrorResponseToPgError((*pgproto3.ErrorResponse)(msg))
  861. return (*Notice)(pgerr)
  862. }
  863. // CancelRequest sends a cancel request to the PostgreSQL server. It returns an error if unable to deliver the cancel
  864. // request, but lack of an error does not ensure that the query was canceled. As specified in the documentation, there
  865. // is no way to be sure a query was canceled.
  866. // See https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-CANCELING-REQUESTS
  867. func (pgConn *PgConn) CancelRequest(ctx context.Context) error {
  868. // Open a cancellation request to the same server. The address is taken from the net.Conn directly instead of reusing
  869. // the connection config. This is important in high availability configurations where fallback connections may be
  870. // specified or DNS may be used to load balance.
  871. serverAddr := pgConn.conn.RemoteAddr()
  872. var serverNetwork string
  873. var serverAddress string
  874. if serverAddr.Network() == "unix" {
  875. // for unix sockets, RemoteAddr() calls getpeername() which returns the name the
  876. // server passed to bind(). For Postgres, this is always a relative path "./.s.PGSQL.5432"
  877. // so connecting to it will fail. Fall back to the config's value
  878. serverNetwork, serverAddress = NetworkAddress(pgConn.config.Host, pgConn.config.Port)
  879. } else {
  880. serverNetwork, serverAddress = serverAddr.Network(), serverAddr.String()
  881. }
  882. cancelConn, err := pgConn.config.DialFunc(ctx, serverNetwork, serverAddress)
  883. if err != nil {
  884. // In case of unix sockets, RemoteAddr() returns only the file part of the path. If the
  885. // first connect failed, try the config.
  886. if serverAddr.Network() != "unix" {
  887. return err
  888. }
  889. serverNetwork, serverAddr := NetworkAddress(pgConn.config.Host, pgConn.config.Port)
  890. cancelConn, err = pgConn.config.DialFunc(ctx, serverNetwork, serverAddr)
  891. if err != nil {
  892. return err
  893. }
  894. }
  895. defer cancelConn.Close()
  896. if ctx != context.Background() {
  897. contextWatcher := ctxwatch.NewContextWatcher(&DeadlineContextWatcherHandler{Conn: cancelConn})
  898. contextWatcher.Watch(ctx)
  899. defer contextWatcher.Unwatch()
  900. }
  901. buf := make([]byte, 16)
  902. binary.BigEndian.PutUint32(buf[0:4], 16)
  903. binary.BigEndian.PutUint32(buf[4:8], 80877102)
  904. binary.BigEndian.PutUint32(buf[8:12], pgConn.pid)
  905. binary.BigEndian.PutUint32(buf[12:16], pgConn.secretKey)
  906. if _, err := cancelConn.Write(buf); err != nil {
  907. return fmt.Errorf("write to connection for cancellation: %w", err)
  908. }
  909. // Wait for the cancel request to be acknowledged by the server.
  910. // It copies the behavior of the libpq: https://github.com/postgres/postgres/blob/REL_16_0/src/interfaces/libpq/fe-connect.c#L4946-L4960
  911. _, _ = cancelConn.Read(buf)
  912. return nil
  913. }
  914. // WaitForNotification waits for a LISTEN/NOTIFY message to be received. It returns an error if a notification was not
  915. // received.
  916. func (pgConn *PgConn) WaitForNotification(ctx context.Context) error {
  917. if err := pgConn.lock(); err != nil {
  918. return err
  919. }
  920. defer pgConn.unlock()
  921. if ctx != context.Background() {
  922. select {
  923. case <-ctx.Done():
  924. return newContextAlreadyDoneError(ctx)
  925. default:
  926. }
  927. pgConn.contextWatcher.Watch(ctx)
  928. defer pgConn.contextWatcher.Unwatch()
  929. }
  930. for {
  931. msg, err := pgConn.receiveMessage()
  932. if err != nil {
  933. return normalizeTimeoutError(ctx, err)
  934. }
  935. switch msg.(type) {
  936. case *pgproto3.NotificationResponse:
  937. return nil
  938. }
  939. }
  940. }
  941. // Exec executes SQL via the PostgreSQL simple query protocol. SQL may contain multiple queries. Execution is
  942. // implicitly wrapped in a transaction unless a transaction is already in progress or SQL contains transaction control
  943. // statements.
  944. //
  945. // Prefer ExecParams unless executing arbitrary SQL that may contain multiple queries.
  946. func (pgConn *PgConn) Exec(ctx context.Context, sql string) *MultiResultReader {
  947. if err := pgConn.lock(); err != nil {
  948. return &MultiResultReader{
  949. closed: true,
  950. err: err,
  951. }
  952. }
  953. pgConn.multiResultReader = MultiResultReader{
  954. pgConn: pgConn,
  955. ctx: ctx,
  956. }
  957. multiResult := &pgConn.multiResultReader
  958. if ctx != context.Background() {
  959. select {
  960. case <-ctx.Done():
  961. multiResult.closed = true
  962. multiResult.err = newContextAlreadyDoneError(ctx)
  963. pgConn.unlock()
  964. return multiResult
  965. default:
  966. }
  967. pgConn.contextWatcher.Watch(ctx)
  968. }
  969. pgConn.frontend.SendQuery(&pgproto3.Query{String: sql})
  970. err := pgConn.flushWithPotentialWriteReadDeadlock()
  971. if err != nil {
  972. pgConn.asyncClose()
  973. pgConn.contextWatcher.Unwatch()
  974. multiResult.closed = true
  975. multiResult.err = err
  976. pgConn.unlock()
  977. return multiResult
  978. }
  979. return multiResult
  980. }
  981. // ExecParams executes a command via the PostgreSQL extended query protocol.
  982. //
  983. // sql is a SQL command string. It may only contain one query. Parameter substitution is positional using $1, $2, $3,
  984. // etc.
  985. //
  986. // paramValues are the parameter values. It must be encoded in the format given by paramFormats.
  987. //
  988. // paramOIDs is a slice of data type OIDs for paramValues. If paramOIDs is nil, the server will infer the data type for
  989. // all parameters. Any paramOID element that is 0 that will cause the server to infer the data type for that parameter.
  990. // ExecParams will panic if len(paramOIDs) is not 0, 1, or len(paramValues).
  991. //
  992. // paramFormats is a slice of format codes determining for each paramValue column whether it is encoded in text or
  993. // binary format. If paramFormats is nil all params are text format. ExecParams will panic if
  994. // len(paramFormats) is not 0, 1, or len(paramValues).
  995. //
  996. // resultFormats is a slice of format codes determining for each result column whether it is encoded in text or
  997. // binary format. If resultFormats is nil all results will be in text format.
  998. //
  999. // ResultReader must be closed before PgConn can be used again.
  1000. func (pgConn *PgConn) ExecParams(ctx context.Context, sql string, paramValues [][]byte, paramOIDs []uint32, paramFormats, resultFormats []int16) *ResultReader {
  1001. result := pgConn.execExtendedPrefix(ctx, paramValues)
  1002. if result.closed {
  1003. return result
  1004. }
  1005. pgConn.frontend.SendParse(&pgproto3.Parse{Query: sql, ParameterOIDs: paramOIDs})
  1006. pgConn.frontend.SendBind(&pgproto3.Bind{ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats})
  1007. pgConn.execExtendedSuffix(result)
  1008. return result
  1009. }
  1010. // ExecPrepared enqueues the execution of a prepared statement via the PostgreSQL extended query protocol.
  1011. //
  1012. // paramValues are the parameter values. It must be encoded in the format given by paramFormats.
  1013. //
  1014. // paramFormats is a slice of format codes determining for each paramValue column whether it is encoded in text or
  1015. // binary format. If paramFormats is nil all params are text format. ExecPrepared will panic if
  1016. // len(paramFormats) is not 0, 1, or len(paramValues).
  1017. //
  1018. // resultFormats is a slice of format codes determining for each result column whether it is encoded in text or
  1019. // binary format. If resultFormats is nil all results will be in text format.
  1020. //
  1021. // ResultReader must be closed before PgConn can be used again.
  1022. func (pgConn *PgConn) ExecPrepared(ctx context.Context, stmtName string, paramValues [][]byte, paramFormats, resultFormats []int16) *ResultReader {
  1023. result := pgConn.execExtendedPrefix(ctx, paramValues)
  1024. if result.closed {
  1025. return result
  1026. }
  1027. pgConn.frontend.SendBind(&pgproto3.Bind{PreparedStatement: stmtName, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats})
  1028. pgConn.execExtendedSuffix(result)
  1029. return result
  1030. }
  1031. func (pgConn *PgConn) execExtendedPrefix(ctx context.Context, paramValues [][]byte) *ResultReader {
  1032. pgConn.resultReader = ResultReader{
  1033. pgConn: pgConn,
  1034. ctx: ctx,
  1035. }
  1036. result := &pgConn.resultReader
  1037. if err := pgConn.lock(); err != nil {
  1038. result.concludeCommand(CommandTag{}, err)
  1039. result.closed = true
  1040. return result
  1041. }
  1042. if len(paramValues) > math.MaxUint16 {
  1043. result.concludeCommand(CommandTag{}, fmt.Errorf("extended protocol limited to %v parameters", math.MaxUint16))
  1044. result.closed = true
  1045. pgConn.unlock()
  1046. return result
  1047. }
  1048. if ctx != context.Background() {
  1049. select {
  1050. case <-ctx.Done():
  1051. result.concludeCommand(CommandTag{}, newContextAlreadyDoneError(ctx))
  1052. result.closed = true
  1053. pgConn.unlock()
  1054. return result
  1055. default:
  1056. }
  1057. pgConn.contextWatcher.Watch(ctx)
  1058. }
  1059. return result
  1060. }
  1061. func (pgConn *PgConn) execExtendedSuffix(result *ResultReader) {
  1062. pgConn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'P'})
  1063. pgConn.frontend.SendExecute(&pgproto3.Execute{})
  1064. pgConn.frontend.SendSync(&pgproto3.Sync{})
  1065. err := pgConn.flushWithPotentialWriteReadDeadlock()
  1066. if err != nil {
  1067. pgConn.asyncClose()
  1068. result.concludeCommand(CommandTag{}, err)
  1069. pgConn.contextWatcher.Unwatch()
  1070. result.closed = true
  1071. pgConn.unlock()
  1072. return
  1073. }
  1074. result.readUntilRowDescription()
  1075. }
  1076. // CopyTo executes the copy command sql and copies the results to w.
  1077. func (pgConn *PgConn) CopyTo(ctx context.Context, w io.Writer, sql string) (CommandTag, error) {
  1078. if err := pgConn.lock(); err != nil {
  1079. return CommandTag{}, err
  1080. }
  1081. if ctx != context.Background() {
  1082. select {
  1083. case <-ctx.Done():
  1084. pgConn.unlock()
  1085. return CommandTag{}, newContextAlreadyDoneError(ctx)
  1086. default:
  1087. }
  1088. pgConn.contextWatcher.Watch(ctx)
  1089. defer pgConn.contextWatcher.Unwatch()
  1090. }
  1091. // Send copy to command
  1092. pgConn.frontend.SendQuery(&pgproto3.Query{String: sql})
  1093. err := pgConn.flushWithPotentialWriteReadDeadlock()
  1094. if err != nil {
  1095. pgConn.asyncClose()
  1096. pgConn.unlock()
  1097. return CommandTag{}, err
  1098. }
  1099. // Read results
  1100. var commandTag CommandTag
  1101. var pgErr error
  1102. for {
  1103. msg, err := pgConn.receiveMessage()
  1104. if err != nil {
  1105. pgConn.asyncClose()
  1106. return CommandTag{}, normalizeTimeoutError(ctx, err)
  1107. }
  1108. switch msg := msg.(type) {
  1109. case *pgproto3.CopyDone:
  1110. case *pgproto3.CopyData:
  1111. _, err := w.Write(msg.Data)
  1112. if err != nil {
  1113. pgConn.asyncClose()
  1114. return CommandTag{}, err
  1115. }
  1116. case *pgproto3.ReadyForQuery:
  1117. pgConn.unlock()
  1118. return commandTag, pgErr
  1119. case *pgproto3.CommandComplete:
  1120. commandTag = pgConn.makeCommandTag(msg.CommandTag)
  1121. case *pgproto3.ErrorResponse:
  1122. pgErr = ErrorResponseToPgError(msg)
  1123. }
  1124. }
  1125. }
  1126. // CopyFrom executes the copy command sql and copies all of r to the PostgreSQL server.
  1127. //
  1128. // Note: context cancellation will only interrupt operations on the underlying PostgreSQL network connection. Reads on r
  1129. // could still block.
  1130. func (pgConn *PgConn) CopyFrom(ctx context.Context, r io.Reader, sql string) (CommandTag, error) {
  1131. if err := pgConn.lock(); err != nil {
  1132. return CommandTag{}, err
  1133. }
  1134. defer pgConn.unlock()
  1135. if ctx != context.Background() {
  1136. select {
  1137. case <-ctx.Done():
  1138. return CommandTag{}, newContextAlreadyDoneError(ctx)
  1139. default:
  1140. }
  1141. pgConn.contextWatcher.Watch(ctx)
  1142. defer pgConn.contextWatcher.Unwatch()
  1143. }
  1144. // Send copy from query
  1145. pgConn.frontend.SendQuery(&pgproto3.Query{String: sql})
  1146. err := pgConn.flushWithPotentialWriteReadDeadlock()
  1147. if err != nil {
  1148. pgConn.asyncClose()
  1149. return CommandTag{}, err
  1150. }
  1151. // Send copy data
  1152. abortCopyChan := make(chan struct{})
  1153. copyErrChan := make(chan error, 1)
  1154. signalMessageChan := pgConn.signalMessage()
  1155. var wg sync.WaitGroup
  1156. wg.Add(1)
  1157. go func() {
  1158. defer wg.Done()
  1159. buf := iobufpool.Get(65536)
  1160. defer iobufpool.Put(buf)
  1161. (*buf)[0] = 'd'
  1162. for {
  1163. n, readErr := r.Read((*buf)[5:cap(*buf)])
  1164. if n > 0 {
  1165. *buf = (*buf)[0 : n+5]
  1166. pgio.SetInt32((*buf)[1:], int32(n+4))
  1167. writeErr := pgConn.frontend.SendUnbufferedEncodedCopyData(*buf)
  1168. if writeErr != nil {
  1169. // Write errors are always fatal, but we can't use asyncClose because we are in a different goroutine. Not
  1170. // setting pgConn.status or closing pgConn.cleanupDone for the same reason.
  1171. pgConn.conn.Close()
  1172. copyErrChan <- writeErr
  1173. return
  1174. }
  1175. }
  1176. if readErr != nil {
  1177. copyErrChan <- readErr
  1178. return
  1179. }
  1180. select {
  1181. case <-abortCopyChan:
  1182. return
  1183. default:
  1184. }
  1185. }
  1186. }()
  1187. var pgErr error
  1188. var copyErr error
  1189. for copyErr == nil && pgErr == nil {
  1190. select {
  1191. case copyErr = <-copyErrChan:
  1192. case <-signalMessageChan:
  1193. // If pgConn.receiveMessage encounters an error it will call pgConn.asyncClose. But that is a race condition with
  1194. // the goroutine. So instead check pgConn.bufferingReceiveErr which will have been set by the signalMessage. If an
  1195. // error is found then forcibly close the connection without sending the Terminate message.
  1196. if err := pgConn.bufferingReceiveErr; err != nil {
  1197. pgConn.status = connStatusClosed
  1198. pgConn.conn.Close()
  1199. close(pgConn.cleanupDone)
  1200. return CommandTag{}, normalizeTimeoutError(ctx, err)
  1201. }
  1202. // peekMessage never returns err in the bufferingReceive mode - it only forwards the bufferingReceive variables.
  1203. // Therefore, the only case for receiveMessage to return err is during handling of the ErrorResponse message type
  1204. // and using pgOnError handler to determine the connection is no longer valid (and thus closing the conn).
  1205. msg, serverError := pgConn.receiveMessage()
  1206. if serverError != nil {
  1207. close(abortCopyChan)
  1208. return CommandTag{}, serverError
  1209. }
  1210. switch msg := msg.(type) {
  1211. case *pgproto3.ErrorResponse:
  1212. pgErr = ErrorResponseToPgError(msg)
  1213. default:
  1214. signalMessageChan = pgConn.signalMessage()
  1215. }
  1216. }
  1217. }
  1218. close(abortCopyChan)
  1219. // Make sure io goroutine finishes before writing.
  1220. wg.Wait()
  1221. if copyErr == io.EOF || pgErr != nil {
  1222. pgConn.frontend.Send(&pgproto3.CopyDone{})
  1223. } else {
  1224. pgConn.frontend.Send(&pgproto3.CopyFail{Message: copyErr.Error()})
  1225. }
  1226. err = pgConn.flushWithPotentialWriteReadDeadlock()
  1227. if err != nil {
  1228. pgConn.asyncClose()
  1229. return CommandTag{}, err
  1230. }
  1231. // Read results
  1232. var commandTag CommandTag
  1233. for {
  1234. msg, err := pgConn.receiveMessage()
  1235. if err != nil {
  1236. pgConn.asyncClose()
  1237. return CommandTag{}, normalizeTimeoutError(ctx, err)
  1238. }
  1239. switch msg := msg.(type) {
  1240. case *pgproto3.ReadyForQuery:
  1241. return commandTag, pgErr
  1242. case *pgproto3.CommandComplete:
  1243. commandTag = pgConn.makeCommandTag(msg.CommandTag)
  1244. case *pgproto3.ErrorResponse:
  1245. pgErr = ErrorResponseToPgError(msg)
  1246. }
  1247. }
  1248. }
  1249. // MultiResultReader is a reader for a command that could return multiple results such as Exec or ExecBatch.
  1250. type MultiResultReader struct {
  1251. pgConn *PgConn
  1252. ctx context.Context
  1253. rr *ResultReader
  1254. closed bool
  1255. err error
  1256. }
  1257. // ReadAll reads all available results. Calling ReadAll is mutually exclusive with all other MultiResultReader methods.
  1258. func (mrr *MultiResultReader) ReadAll() ([]*Result, error) {
  1259. var results []*Result
  1260. for mrr.NextResult() {
  1261. results = append(results, mrr.ResultReader().Read())
  1262. }
  1263. err := mrr.Close()
  1264. return results, err
  1265. }
  1266. func (mrr *MultiResultReader) receiveMessage() (pgproto3.BackendMessage, error) {
  1267. msg, err := mrr.pgConn.receiveMessage()
  1268. if err != nil {
  1269. mrr.pgConn.contextWatcher.Unwatch()
  1270. mrr.err = normalizeTimeoutError(mrr.ctx, err)
  1271. mrr.closed = true
  1272. mrr.pgConn.asyncClose()
  1273. return nil, mrr.err
  1274. }
  1275. switch msg := msg.(type) {
  1276. case *pgproto3.ReadyForQuery:
  1277. mrr.closed = true
  1278. mrr.pgConn.contextWatcher.Unwatch()
  1279. mrr.pgConn.unlock()
  1280. case *pgproto3.ErrorResponse:
  1281. mrr.err = ErrorResponseToPgError(msg)
  1282. }
  1283. return msg, nil
  1284. }
  1285. // NextResult returns advances the MultiResultReader to the next result and returns true if a result is available.
  1286. func (mrr *MultiResultReader) NextResult() bool {
  1287. for !mrr.closed && mrr.err == nil {
  1288. msg, err := mrr.receiveMessage()
  1289. if err != nil {
  1290. return false
  1291. }
  1292. switch msg := msg.(type) {
  1293. case *pgproto3.RowDescription:
  1294. mrr.pgConn.resultReader = ResultReader{
  1295. pgConn: mrr.pgConn,
  1296. multiResultReader: mrr,
  1297. ctx: mrr.ctx,
  1298. fieldDescriptions: mrr.pgConn.convertRowDescription(mrr.pgConn.fieldDescriptions[:], msg),
  1299. }
  1300. mrr.rr = &mrr.pgConn.resultReader
  1301. return true
  1302. case *pgproto3.CommandComplete:
  1303. mrr.pgConn.resultReader = ResultReader{
  1304. commandTag: mrr.pgConn.makeCommandTag(msg.CommandTag),
  1305. commandConcluded: true,
  1306. closed: true,
  1307. }
  1308. mrr.rr = &mrr.pgConn.resultReader
  1309. return true
  1310. case *pgproto3.EmptyQueryResponse:
  1311. mrr.pgConn.resultReader = ResultReader{
  1312. commandConcluded: true,
  1313. closed: true,
  1314. }
  1315. mrr.rr = &mrr.pgConn.resultReader
  1316. return true
  1317. }
  1318. }
  1319. return false
  1320. }
  1321. // ResultReader returns the current ResultReader.
  1322. func (mrr *MultiResultReader) ResultReader() *ResultReader {
  1323. return mrr.rr
  1324. }
  1325. // Close closes the MultiResultReader and returns the first error that occurred during the MultiResultReader's use.
  1326. func (mrr *MultiResultReader) Close() error {
  1327. for !mrr.closed {
  1328. _, err := mrr.receiveMessage()
  1329. if err != nil {
  1330. return mrr.err
  1331. }
  1332. }
  1333. return mrr.err
  1334. }
  1335. // ResultReader is a reader for the result of a single query.
  1336. type ResultReader struct {
  1337. pgConn *PgConn
  1338. multiResultReader *MultiResultReader
  1339. pipeline *Pipeline
  1340. ctx context.Context
  1341. fieldDescriptions []FieldDescription
  1342. rowValues [][]byte
  1343. commandTag CommandTag
  1344. commandConcluded bool
  1345. closed bool
  1346. err error
  1347. }
  1348. // Result is the saved query response that is returned by calling Read on a ResultReader.
  1349. type Result struct {
  1350. FieldDescriptions []FieldDescription
  1351. Rows [][][]byte
  1352. CommandTag CommandTag
  1353. Err error
  1354. }
  1355. // Read saves the query response to a Result.
  1356. func (rr *ResultReader) Read() *Result {
  1357. br := &Result{}
  1358. for rr.NextRow() {
  1359. if br.FieldDescriptions == nil {
  1360. br.FieldDescriptions = make([]FieldDescription, len(rr.FieldDescriptions()))
  1361. copy(br.FieldDescriptions, rr.FieldDescriptions())
  1362. }
  1363. values := rr.Values()
  1364. row := make([][]byte, len(values))
  1365. for i := range row {
  1366. if values[i] != nil {
  1367. row[i] = make([]byte, len(values[i]))
  1368. copy(row[i], values[i])
  1369. }
  1370. }
  1371. br.Rows = append(br.Rows, row)
  1372. }
  1373. br.CommandTag, br.Err = rr.Close()
  1374. return br
  1375. }
  1376. // NextRow advances the ResultReader to the next row and returns true if a row is available.
  1377. func (rr *ResultReader) NextRow() bool {
  1378. for !rr.commandConcluded {
  1379. msg, err := rr.receiveMessage()
  1380. if err != nil {
  1381. return false
  1382. }
  1383. switch msg := msg.(type) {
  1384. case *pgproto3.DataRow:
  1385. rr.rowValues = msg.Values
  1386. return true
  1387. }
  1388. }
  1389. return false
  1390. }
  1391. // FieldDescriptions returns the field descriptions for the current result set. The returned slice is only valid until
  1392. // the ResultReader is closed. It may return nil (for example, if the query did not return a result set or an error was
  1393. // encountered.)
  1394. func (rr *ResultReader) FieldDescriptions() []FieldDescription {
  1395. return rr.fieldDescriptions
  1396. }
  1397. // Values returns the current row data. NextRow must have been previously been called. The returned [][]byte is only
  1398. // valid until the next NextRow call or the ResultReader is closed.
  1399. func (rr *ResultReader) Values() [][]byte {
  1400. return rr.rowValues
  1401. }
  1402. // Close consumes any remaining result data and returns the command tag or
  1403. // error.
  1404. func (rr *ResultReader) Close() (CommandTag, error) {
  1405. if rr.closed {
  1406. return rr.commandTag, rr.err
  1407. }
  1408. rr.closed = true
  1409. for !rr.commandConcluded {
  1410. _, err := rr.receiveMessage()
  1411. if err != nil {
  1412. return CommandTag{}, rr.err
  1413. }
  1414. }
  1415. if rr.multiResultReader == nil && rr.pipeline == nil {
  1416. for {
  1417. msg, err := rr.receiveMessage()
  1418. if err != nil {
  1419. return CommandTag{}, rr.err
  1420. }
  1421. switch msg := msg.(type) {
  1422. // Detect a deferred constraint violation where the ErrorResponse is sent after CommandComplete.
  1423. case *pgproto3.ErrorResponse:
  1424. rr.err = ErrorResponseToPgError(msg)
  1425. case *pgproto3.ReadyForQuery:
  1426. rr.pgConn.contextWatcher.Unwatch()
  1427. rr.pgConn.unlock()
  1428. return rr.commandTag, rr.err
  1429. }
  1430. }
  1431. }
  1432. return rr.commandTag, rr.err
  1433. }
  1434. // readUntilRowDescription ensures the ResultReader's fieldDescriptions are loaded. It does not return an error as any
  1435. // error will be stored in the ResultReader.
  1436. func (rr *ResultReader) readUntilRowDescription() {
  1437. for !rr.commandConcluded {
  1438. // Peek before receive to avoid consuming a DataRow if the result set does not include a RowDescription method.
  1439. // This should never happen under normal pgconn usage, but it is possible if SendBytes and ReceiveResults are
  1440. // manually used to construct a query that does not issue a describe statement.
  1441. msg, _ := rr.pgConn.peekMessage()
  1442. if _, ok := msg.(*pgproto3.DataRow); ok {
  1443. return
  1444. }
  1445. // Consume the message
  1446. msg, _ = rr.receiveMessage()
  1447. if _, ok := msg.(*pgproto3.RowDescription); ok {
  1448. return
  1449. }
  1450. }
  1451. }
  1452. func (rr *ResultReader) receiveMessage() (msg pgproto3.BackendMessage, err error) {
  1453. if rr.multiResultReader == nil {
  1454. msg, err = rr.pgConn.receiveMessage()
  1455. } else {
  1456. msg, err = rr.multiResultReader.receiveMessage()
  1457. }
  1458. if err != nil {
  1459. err = normalizeTimeoutError(rr.ctx, err)
  1460. rr.concludeCommand(CommandTag{}, err)
  1461. rr.pgConn.contextWatcher.Unwatch()
  1462. rr.closed = true
  1463. if rr.multiResultReader == nil {
  1464. rr.pgConn.asyncClose()
  1465. }
  1466. return nil, rr.err
  1467. }
  1468. switch msg := msg.(type) {
  1469. case *pgproto3.RowDescription:
  1470. rr.fieldDescriptions = rr.pgConn.convertRowDescription(rr.pgConn.fieldDescriptions[:], msg)
  1471. case *pgproto3.CommandComplete:
  1472. rr.concludeCommand(rr.pgConn.makeCommandTag(msg.CommandTag), nil)
  1473. case *pgproto3.EmptyQueryResponse:
  1474. rr.concludeCommand(CommandTag{}, nil)
  1475. case *pgproto3.ErrorResponse:
  1476. pgErr := ErrorResponseToPgError(msg)
  1477. if rr.pipeline != nil {
  1478. rr.pipeline.state.HandleError(pgErr)
  1479. }
  1480. rr.concludeCommand(CommandTag{}, pgErr)
  1481. }
  1482. return msg, nil
  1483. }
  1484. func (rr *ResultReader) concludeCommand(commandTag CommandTag, err error) {
  1485. // Keep the first error that is recorded. Store the error before checking if the command is already concluded to
  1486. // allow for receiving an error after CommandComplete but before ReadyForQuery.
  1487. if err != nil && rr.err == nil {
  1488. rr.err = err
  1489. }
  1490. if rr.commandConcluded {
  1491. return
  1492. }
  1493. rr.commandTag = commandTag
  1494. rr.rowValues = nil
  1495. rr.commandConcluded = true
  1496. }
  1497. // Batch is a collection of queries that can be sent to the PostgreSQL server in a single round-trip.
  1498. type Batch struct {
  1499. buf []byte
  1500. err error
  1501. }
  1502. // ExecParams appends an ExecParams command to the batch. See PgConn.ExecParams for parameter descriptions.
  1503. func (batch *Batch) ExecParams(sql string, paramValues [][]byte, paramOIDs []uint32, paramFormats, resultFormats []int16) {
  1504. if batch.err != nil {
  1505. return
  1506. }
  1507. batch.buf, batch.err = (&pgproto3.Parse{Query: sql, ParameterOIDs: paramOIDs}).Encode(batch.buf)
  1508. if batch.err != nil {
  1509. return
  1510. }
  1511. batch.ExecPrepared("", paramValues, paramFormats, resultFormats)
  1512. }
  1513. // ExecPrepared appends an ExecPrepared e command to the batch. See PgConn.ExecPrepared for parameter descriptions.
  1514. func (batch *Batch) ExecPrepared(stmtName string, paramValues [][]byte, paramFormats, resultFormats []int16) {
  1515. if batch.err != nil {
  1516. return
  1517. }
  1518. batch.buf, batch.err = (&pgproto3.Bind{PreparedStatement: stmtName, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}).Encode(batch.buf)
  1519. if batch.err != nil {
  1520. return
  1521. }
  1522. batch.buf, batch.err = (&pgproto3.Describe{ObjectType: 'P'}).Encode(batch.buf)
  1523. if batch.err != nil {
  1524. return
  1525. }
  1526. batch.buf, batch.err = (&pgproto3.Execute{}).Encode(batch.buf)
  1527. if batch.err != nil {
  1528. return
  1529. }
  1530. }
  1531. // ExecBatch executes all the queries in batch in a single round-trip. Execution is implicitly transactional unless a
  1532. // transaction is already in progress or SQL contains transaction control statements. This is a simpler way of executing
  1533. // multiple queries in a single round trip than using pipeline mode.
  1534. func (pgConn *PgConn) ExecBatch(ctx context.Context, batch *Batch) *MultiResultReader {
  1535. if batch.err != nil {
  1536. return &MultiResultReader{
  1537. closed: true,
  1538. err: batch.err,
  1539. }
  1540. }
  1541. if err := pgConn.lock(); err != nil {
  1542. return &MultiResultReader{
  1543. closed: true,
  1544. err: err,
  1545. }
  1546. }
  1547. pgConn.multiResultReader = MultiResultReader{
  1548. pgConn: pgConn,
  1549. ctx: ctx,
  1550. }
  1551. multiResult := &pgConn.multiResultReader
  1552. if ctx != context.Background() {
  1553. select {
  1554. case <-ctx.Done():
  1555. multiResult.closed = true
  1556. multiResult.err = newContextAlreadyDoneError(ctx)
  1557. pgConn.unlock()
  1558. return multiResult
  1559. default:
  1560. }
  1561. pgConn.contextWatcher.Watch(ctx)
  1562. }
  1563. batch.buf, batch.err = (&pgproto3.Sync{}).Encode(batch.buf)
  1564. if batch.err != nil {
  1565. pgConn.contextWatcher.Unwatch()
  1566. multiResult.err = normalizeTimeoutError(multiResult.ctx, batch.err)
  1567. multiResult.closed = true
  1568. pgConn.asyncClose()
  1569. return multiResult
  1570. }
  1571. pgConn.enterPotentialWriteReadDeadlock()
  1572. defer pgConn.exitPotentialWriteReadDeadlock()
  1573. _, err := pgConn.conn.Write(batch.buf)
  1574. if err != nil {
  1575. pgConn.contextWatcher.Unwatch()
  1576. multiResult.err = normalizeTimeoutError(multiResult.ctx, err)
  1577. multiResult.closed = true
  1578. pgConn.asyncClose()
  1579. return multiResult
  1580. }
  1581. return multiResult
  1582. }
  1583. // EscapeString escapes a string such that it can safely be interpolated into a SQL command string. It does not include
  1584. // the surrounding single quotes.
  1585. //
  1586. // The current implementation requires that standard_conforming_strings=on and client_encoding="UTF8". If these
  1587. // conditions are not met an error will be returned. It is possible these restrictions will be lifted in the future.
  1588. func (pgConn *PgConn) EscapeString(s string) (string, error) {
  1589. if pgConn.ParameterStatus("standard_conforming_strings") != "on" {
  1590. return "", errors.New("EscapeString must be run with standard_conforming_strings=on")
  1591. }
  1592. if pgConn.ParameterStatus("client_encoding") != "UTF8" {
  1593. return "", errors.New("EscapeString must be run with client_encoding=UTF8")
  1594. }
  1595. return strings.Replace(s, "'", "''", -1), nil
  1596. }
  1597. // CheckConn checks the underlying connection without writing any bytes. This is currently implemented by doing a read
  1598. // with a very short deadline. This can be useful because a TCP connection can be broken such that a write will appear
  1599. // to succeed even though it will never actually reach the server. Reading immediately before a write will detect this
  1600. // condition. If this is done immediately before sending a query it reduces the chances a query will be sent that fails
  1601. // without the client knowing whether the server received it or not.
  1602. //
  1603. // Deprecated: CheckConn is deprecated in favor of Ping. CheckConn cannot detect all types of broken connections where
  1604. // the write would still appear to succeed. Prefer Ping unless on a high latency connection.
  1605. func (pgConn *PgConn) CheckConn() error {
  1606. ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
  1607. defer cancel()
  1608. _, err := pgConn.ReceiveMessage(ctx)
  1609. if err != nil {
  1610. if !Timeout(err) {
  1611. return err
  1612. }
  1613. }
  1614. return nil
  1615. }
  1616. // Ping pings the server. This can be useful because a TCP connection can be broken such that a write will appear to
  1617. // succeed even though it will never actually reach the server. Pinging immediately before sending a query reduces the
  1618. // chances a query will be sent that fails without the client knowing whether the server received it or not.
  1619. func (pgConn *PgConn) Ping(ctx context.Context) error {
  1620. return pgConn.Exec(ctx, "-- ping").Close()
  1621. }
  1622. // makeCommandTag makes a CommandTag. It does not retain a reference to buf or buf's underlying memory.
  1623. func (pgConn *PgConn) makeCommandTag(buf []byte) CommandTag {
  1624. return CommandTag{s: string(buf)}
  1625. }
  1626. // enterPotentialWriteReadDeadlock must be called before a write that could deadlock if the server is simultaneously
  1627. // blocked writing to us.
  1628. func (pgConn *PgConn) enterPotentialWriteReadDeadlock() {
  1629. // The time to wait is somewhat arbitrary. A Write should only take as long as the syscall and memcpy to the OS
  1630. // outbound network buffer unless the buffer is full (which potentially is a block). It needs to be long enough for
  1631. // the normal case, but short enough not to kill performance if a block occurs.
  1632. //
  1633. // In addition, on Windows the default timer resolution is 15.6ms. So setting the timer to less than that is
  1634. // ineffective.
  1635. if pgConn.slowWriteTimer.Reset(15 * time.Millisecond) {
  1636. panic("BUG: slow write timer already active")
  1637. }
  1638. }
  1639. // exitPotentialWriteReadDeadlock must be called after a call to enterPotentialWriteReadDeadlock.
  1640. func (pgConn *PgConn) exitPotentialWriteReadDeadlock() {
  1641. if !pgConn.slowWriteTimer.Stop() {
  1642. // The timer starts its function in a separate goroutine. It is necessary to ensure the background reader has
  1643. // started before calling Stop. Otherwise, the background reader may not be stopped. That on its own is not a
  1644. // serious problem. But what is a serious problem is that the background reader may start at an inopportune time in
  1645. // a subsequent query. For example, if a subsequent query was canceled then a deadline may be set on the net.Conn to
  1646. // interrupt an in-progress read. After the read is interrupted, but before the deadline is cleared, the background
  1647. // reader could start and read a deadline error. Then the next query would receive the an unexpected deadline error.
  1648. <-pgConn.bgReaderStarted
  1649. pgConn.bgReader.Stop()
  1650. }
  1651. }
  1652. func (pgConn *PgConn) flushWithPotentialWriteReadDeadlock() error {
  1653. pgConn.enterPotentialWriteReadDeadlock()
  1654. defer pgConn.exitPotentialWriteReadDeadlock()
  1655. err := pgConn.frontend.Flush()
  1656. return err
  1657. }
  1658. // SyncConn prepares the underlying net.Conn for direct use. PgConn may internally buffer reads or use goroutines for
  1659. // background IO. This means that any direct use of the underlying net.Conn may be corrupted if a read is already
  1660. // buffered or a read is in progress. SyncConn drains read buffers and stops background IO. In some cases this may
  1661. // require sending a ping to the server. ctx can be used to cancel this operation. This should be called before any
  1662. // operation that will use the underlying net.Conn directly. e.g. Before Conn() or Hijack().
  1663. //
  1664. // This should not be confused with the PostgreSQL protocol Sync message.
  1665. func (pgConn *PgConn) SyncConn(ctx context.Context) error {
  1666. for range 10 {
  1667. if pgConn.bgReader.Status() == bgreader.StatusStopped && pgConn.frontend.ReadBufferLen() == 0 {
  1668. return nil
  1669. }
  1670. err := pgConn.Ping(ctx)
  1671. if err != nil {
  1672. return fmt.Errorf("SyncConn: Ping failed while syncing conn: %w", err)
  1673. }
  1674. }
  1675. // This should never happen. Only way I can imagine this occurring is if the server is constantly sending data such as
  1676. // LISTEN/NOTIFY or log notifications such that we never can get an empty buffer.
  1677. return errors.New("SyncConn: conn never synchronized")
  1678. }
  1679. // CustomData returns a map that can be used to associate custom data with the connection.
  1680. func (pgConn *PgConn) CustomData() map[string]any {
  1681. return pgConn.customData
  1682. }
  1683. // HijackedConn is the result of hijacking a connection.
  1684. //
  1685. // Due to the necessary exposure of internal implementation details, it is not covered by the semantic versioning
  1686. // compatibility.
  1687. type HijackedConn struct {
  1688. Conn net.Conn
  1689. PID uint32 // backend pid
  1690. SecretKey uint32 // key to use to send a cancel query message to the server
  1691. ParameterStatuses map[string]string // parameters that have been reported by the server
  1692. TxStatus byte
  1693. Frontend *pgproto3.Frontend
  1694. Config *Config
  1695. CustomData map[string]any
  1696. }
  1697. // Hijack extracts the internal connection data. pgConn must be in an idle state. SyncConn should be called immediately
  1698. // before Hijack. pgConn is unusable after hijacking. Hijacking is typically only useful when using pgconn to establish
  1699. // a connection, but taking complete control of the raw connection after that (e.g. a load balancer or proxy).
  1700. //
  1701. // Due to the necessary exposure of internal implementation details, it is not covered by the semantic versioning
  1702. // compatibility.
  1703. func (pgConn *PgConn) Hijack() (*HijackedConn, error) {
  1704. if err := pgConn.lock(); err != nil {
  1705. return nil, err
  1706. }
  1707. pgConn.status = connStatusClosed
  1708. return &HijackedConn{
  1709. Conn: pgConn.conn,
  1710. PID: pgConn.pid,
  1711. SecretKey: pgConn.secretKey,
  1712. ParameterStatuses: pgConn.parameterStatuses,
  1713. TxStatus: pgConn.txStatus,
  1714. Frontend: pgConn.frontend,
  1715. Config: pgConn.config,
  1716. CustomData: pgConn.customData,
  1717. }, nil
  1718. }
  1719. // Construct created a PgConn from an already established connection to a PostgreSQL server. This is the inverse of
  1720. // PgConn.Hijack. The connection must be in an idle state.
  1721. //
  1722. // hc.Frontend is replaced by a new pgproto3.Frontend built by hc.Config.BuildFrontend.
  1723. //
  1724. // Due to the necessary exposure of internal implementation details, it is not covered by the semantic versioning
  1725. // compatibility.
  1726. func Construct(hc *HijackedConn) (*PgConn, error) {
  1727. pgConn := &PgConn{
  1728. conn: hc.Conn,
  1729. pid: hc.PID,
  1730. secretKey: hc.SecretKey,
  1731. parameterStatuses: hc.ParameterStatuses,
  1732. txStatus: hc.TxStatus,
  1733. frontend: hc.Frontend,
  1734. config: hc.Config,
  1735. customData: hc.CustomData,
  1736. status: connStatusIdle,
  1737. cleanupDone: make(chan struct{}),
  1738. }
  1739. pgConn.contextWatcher = ctxwatch.NewContextWatcher(hc.Config.BuildContextWatcherHandler(pgConn))
  1740. pgConn.bgReader = bgreader.New(pgConn.conn)
  1741. pgConn.slowWriteTimer = time.AfterFunc(time.Duration(math.MaxInt64),
  1742. func() {
  1743. pgConn.bgReader.Start()
  1744. pgConn.bgReaderStarted <- struct{}{}
  1745. },
  1746. )
  1747. pgConn.slowWriteTimer.Stop()
  1748. pgConn.bgReaderStarted = make(chan struct{})
  1749. pgConn.frontend = hc.Config.BuildFrontend(pgConn.bgReader, pgConn.conn)
  1750. return pgConn, nil
  1751. }
  1752. // Pipeline represents a connection in pipeline mode.
  1753. //
  1754. // SendPrepare, SendQueryParams, and SendQueryPrepared queue requests to the server. These requests are not written until
  1755. // pipeline is flushed by Flush or Sync. Sync must be called after the last request is queued. Requests between
  1756. // synchronization points are implicitly transactional unless explicit transaction control statements have been issued.
  1757. //
  1758. // The context the pipeline was started with is in effect for the entire life of the Pipeline.
  1759. //
  1760. // For a deeper understanding of pipeline mode see the PostgreSQL documentation for the extended query protocol
  1761. // (https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY) and the libpq pipeline mode
  1762. // (https://www.postgresql.org/docs/current/libpq-pipeline-mode.html).
  1763. type Pipeline struct {
  1764. conn *PgConn
  1765. ctx context.Context
  1766. state pipelineState
  1767. err error
  1768. closed bool
  1769. }
  1770. // PipelineSync is returned by GetResults when a ReadyForQuery message is received.
  1771. type PipelineSync struct{}
  1772. // CloseComplete is returned by GetResults when a CloseComplete message is received.
  1773. type CloseComplete struct{}
  1774. type pipelineRequestType int
  1775. const (
  1776. pipelineNil pipelineRequestType = iota
  1777. pipelinePrepare
  1778. pipelineQueryParams
  1779. pipelineQueryPrepared
  1780. pipelineDeallocate
  1781. pipelineSyncRequest
  1782. pipelineFlushRequest
  1783. )
  1784. type pipelineRequestEvent struct {
  1785. RequestType pipelineRequestType
  1786. WasSentToServer bool
  1787. BeforeFlushOrSync bool
  1788. }
  1789. type pipelineState struct {
  1790. requestEventQueue list.List
  1791. lastRequestType pipelineRequestType
  1792. pgErr *PgError
  1793. expectedReadyForQueryCount int
  1794. }
  1795. func (s *pipelineState) Init() {
  1796. s.requestEventQueue.Init()
  1797. s.lastRequestType = pipelineNil
  1798. }
  1799. func (s *pipelineState) RegisterSendingToServer() {
  1800. for elem := s.requestEventQueue.Back(); elem != nil; elem = elem.Prev() {
  1801. val := elem.Value.(pipelineRequestEvent)
  1802. if val.WasSentToServer {
  1803. return
  1804. }
  1805. val.WasSentToServer = true
  1806. elem.Value = val
  1807. }
  1808. }
  1809. func (s *pipelineState) registerFlushingBufferOnServer() {
  1810. for elem := s.requestEventQueue.Back(); elem != nil; elem = elem.Prev() {
  1811. val := elem.Value.(pipelineRequestEvent)
  1812. if val.BeforeFlushOrSync {
  1813. return
  1814. }
  1815. val.BeforeFlushOrSync = true
  1816. elem.Value = val
  1817. }
  1818. }
  1819. func (s *pipelineState) PushBackRequestType(req pipelineRequestType) {
  1820. if req == pipelineNil {
  1821. return
  1822. }
  1823. if req != pipelineFlushRequest {
  1824. s.requestEventQueue.PushBack(pipelineRequestEvent{RequestType: req})
  1825. }
  1826. if req == pipelineFlushRequest || req == pipelineSyncRequest {
  1827. s.registerFlushingBufferOnServer()
  1828. }
  1829. s.lastRequestType = req
  1830. if req == pipelineSyncRequest {
  1831. s.expectedReadyForQueryCount++
  1832. }
  1833. }
  1834. func (s *pipelineState) ExtractFrontRequestType() pipelineRequestType {
  1835. for {
  1836. elem := s.requestEventQueue.Front()
  1837. if elem == nil {
  1838. return pipelineNil
  1839. }
  1840. val := elem.Value.(pipelineRequestEvent)
  1841. if !(val.WasSentToServer && val.BeforeFlushOrSync) {
  1842. return pipelineNil
  1843. }
  1844. s.requestEventQueue.Remove(elem)
  1845. if val.RequestType == pipelineSyncRequest {
  1846. s.pgErr = nil
  1847. }
  1848. if s.pgErr == nil {
  1849. return val.RequestType
  1850. }
  1851. }
  1852. }
  1853. func (s *pipelineState) HandleError(err *PgError) {
  1854. s.pgErr = err
  1855. }
  1856. func (s *pipelineState) HandleReadyForQuery() {
  1857. s.expectedReadyForQueryCount--
  1858. }
  1859. func (s *pipelineState) PendingSync() bool {
  1860. var notPendingSync bool
  1861. if elem := s.requestEventQueue.Back(); elem != nil {
  1862. val := elem.Value.(pipelineRequestEvent)
  1863. notPendingSync = (val.RequestType == pipelineSyncRequest) && val.WasSentToServer
  1864. } else {
  1865. notPendingSync = (s.lastRequestType == pipelineSyncRequest) || (s.lastRequestType == pipelineNil)
  1866. }
  1867. return !notPendingSync
  1868. }
  1869. func (s *pipelineState) ExpectedReadyForQuery() int {
  1870. return s.expectedReadyForQueryCount
  1871. }
  1872. // StartPipeline switches the connection to pipeline mode and returns a *Pipeline. In pipeline mode requests can be sent
  1873. // to the server without waiting for a response. Close must be called on the returned *Pipeline to return the connection
  1874. // to normal mode. While in pipeline mode, no methods that communicate with the server may be called except
  1875. // CancelRequest and Close. ctx is in effect for entire life of the *Pipeline.
  1876. //
  1877. // Prefer ExecBatch when only sending one group of queries at once.
  1878. func (pgConn *PgConn) StartPipeline(ctx context.Context) *Pipeline {
  1879. if err := pgConn.lock(); err != nil {
  1880. pipeline := &Pipeline{
  1881. closed: true,
  1882. err: err,
  1883. }
  1884. pipeline.state.Init()
  1885. return pipeline
  1886. }
  1887. pgConn.pipeline = Pipeline{
  1888. conn: pgConn,
  1889. ctx: ctx,
  1890. }
  1891. pgConn.pipeline.state.Init()
  1892. pipeline := &pgConn.pipeline
  1893. if ctx != context.Background() {
  1894. select {
  1895. case <-ctx.Done():
  1896. pipeline.closed = true
  1897. pipeline.err = newContextAlreadyDoneError(ctx)
  1898. pgConn.unlock()
  1899. return pipeline
  1900. default:
  1901. }
  1902. pgConn.contextWatcher.Watch(ctx)
  1903. }
  1904. return pipeline
  1905. }
  1906. // SendPrepare is the pipeline version of *PgConn.Prepare.
  1907. func (p *Pipeline) SendPrepare(name, sql string, paramOIDs []uint32) {
  1908. if p.closed {
  1909. return
  1910. }
  1911. p.conn.frontend.SendParse(&pgproto3.Parse{Name: name, Query: sql, ParameterOIDs: paramOIDs})
  1912. p.conn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'S', Name: name})
  1913. p.state.PushBackRequestType(pipelinePrepare)
  1914. }
  1915. // SendDeallocate deallocates a prepared statement.
  1916. func (p *Pipeline) SendDeallocate(name string) {
  1917. if p.closed {
  1918. return
  1919. }
  1920. p.conn.frontend.SendClose(&pgproto3.Close{ObjectType: 'S', Name: name})
  1921. p.state.PushBackRequestType(pipelineDeallocate)
  1922. }
  1923. // SendQueryParams is the pipeline version of *PgConn.QueryParams.
  1924. func (p *Pipeline) SendQueryParams(sql string, paramValues [][]byte, paramOIDs []uint32, paramFormats, resultFormats []int16) {
  1925. if p.closed {
  1926. return
  1927. }
  1928. p.conn.frontend.SendParse(&pgproto3.Parse{Query: sql, ParameterOIDs: paramOIDs})
  1929. p.conn.frontend.SendBind(&pgproto3.Bind{ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats})
  1930. p.conn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'P'})
  1931. p.conn.frontend.SendExecute(&pgproto3.Execute{})
  1932. p.state.PushBackRequestType(pipelineQueryParams)
  1933. }
  1934. // SendQueryPrepared is the pipeline version of *PgConn.QueryPrepared.
  1935. func (p *Pipeline) SendQueryPrepared(stmtName string, paramValues [][]byte, paramFormats, resultFormats []int16) {
  1936. if p.closed {
  1937. return
  1938. }
  1939. p.conn.frontend.SendBind(&pgproto3.Bind{PreparedStatement: stmtName, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats})
  1940. p.conn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'P'})
  1941. p.conn.frontend.SendExecute(&pgproto3.Execute{})
  1942. p.state.PushBackRequestType(pipelineQueryPrepared)
  1943. }
  1944. // SendFlushRequest sends a request for the server to flush its output buffer.
  1945. //
  1946. // The server flushes its output buffer automatically as a result of Sync being called,
  1947. // or on any request when not in pipeline mode; this function is useful to cause the server
  1948. // to flush its output buffer in pipeline mode without establishing a synchronization point.
  1949. // Note that the request is not itself flushed to the server automatically; use Flush if
  1950. // necessary. This copies the behavior of libpq PQsendFlushRequest.
  1951. func (p *Pipeline) SendFlushRequest() {
  1952. if p.closed {
  1953. return
  1954. }
  1955. p.conn.frontend.Send(&pgproto3.Flush{})
  1956. p.state.PushBackRequestType(pipelineFlushRequest)
  1957. }
  1958. // SendPipelineSync marks a synchronization point in a pipeline by sending a sync message
  1959. // without flushing the send buffer. This serves as the delimiter of an implicit
  1960. // transaction and an error recovery point.
  1961. //
  1962. // Note that the request is not itself flushed to the server automatically; use Flush if
  1963. // necessary. This copies the behavior of libpq PQsendPipelineSync.
  1964. func (p *Pipeline) SendPipelineSync() {
  1965. if p.closed {
  1966. return
  1967. }
  1968. p.conn.frontend.SendSync(&pgproto3.Sync{})
  1969. p.state.PushBackRequestType(pipelineSyncRequest)
  1970. }
  1971. // Flush flushes the queued requests without establishing a synchronization point.
  1972. func (p *Pipeline) Flush() error {
  1973. if p.closed {
  1974. if p.err != nil {
  1975. return p.err
  1976. }
  1977. return errors.New("pipeline closed")
  1978. }
  1979. err := p.conn.flushWithPotentialWriteReadDeadlock()
  1980. if err != nil {
  1981. err = normalizeTimeoutError(p.ctx, err)
  1982. p.conn.asyncClose()
  1983. p.conn.contextWatcher.Unwatch()
  1984. p.conn.unlock()
  1985. p.closed = true
  1986. p.err = err
  1987. return err
  1988. }
  1989. p.state.RegisterSendingToServer()
  1990. return nil
  1991. }
  1992. // Sync establishes a synchronization point and flushes the queued requests.
  1993. func (p *Pipeline) Sync() error {
  1994. p.SendPipelineSync()
  1995. return p.Flush()
  1996. }
  1997. // GetResults gets the next results. If results are present, results may be a *ResultReader, *StatementDescription, or
  1998. // *PipelineSync. If an ErrorResponse is received from the server, results will be nil and err will be a *PgError. If no
  1999. // results are available, results and err will both be nil.
  2000. func (p *Pipeline) GetResults() (results any, err error) {
  2001. if p.closed {
  2002. if p.err != nil {
  2003. return nil, p.err
  2004. }
  2005. return nil, errors.New("pipeline closed")
  2006. }
  2007. if p.state.ExtractFrontRequestType() == pipelineNil {
  2008. return nil, nil
  2009. }
  2010. return p.getResults()
  2011. }
  2012. func (p *Pipeline) getResults() (results any, err error) {
  2013. for {
  2014. msg, err := p.conn.receiveMessage()
  2015. if err != nil {
  2016. p.closed = true
  2017. p.err = err
  2018. p.conn.asyncClose()
  2019. return nil, normalizeTimeoutError(p.ctx, err)
  2020. }
  2021. switch msg := msg.(type) {
  2022. case *pgproto3.RowDescription:
  2023. p.conn.resultReader = ResultReader{
  2024. pgConn: p.conn,
  2025. pipeline: p,
  2026. ctx: p.ctx,
  2027. fieldDescriptions: p.conn.convertRowDescription(p.conn.fieldDescriptions[:], msg),
  2028. }
  2029. return &p.conn.resultReader, nil
  2030. case *pgproto3.CommandComplete:
  2031. p.conn.resultReader = ResultReader{
  2032. commandTag: p.conn.makeCommandTag(msg.CommandTag),
  2033. commandConcluded: true,
  2034. closed: true,
  2035. }
  2036. return &p.conn.resultReader, nil
  2037. case *pgproto3.ParseComplete:
  2038. peekedMsg, err := p.conn.peekMessage()
  2039. if err != nil {
  2040. p.conn.asyncClose()
  2041. return nil, normalizeTimeoutError(p.ctx, err)
  2042. }
  2043. if _, ok := peekedMsg.(*pgproto3.ParameterDescription); ok {
  2044. return p.getResultsPrepare()
  2045. }
  2046. case *pgproto3.CloseComplete:
  2047. return &CloseComplete{}, nil
  2048. case *pgproto3.ReadyForQuery:
  2049. p.state.HandleReadyForQuery()
  2050. return &PipelineSync{}, nil
  2051. case *pgproto3.ErrorResponse:
  2052. pgErr := ErrorResponseToPgError(msg)
  2053. p.state.HandleError(pgErr)
  2054. return nil, pgErr
  2055. }
  2056. }
  2057. }
  2058. func (p *Pipeline) getResultsPrepare() (*StatementDescription, error) {
  2059. psd := &StatementDescription{}
  2060. for {
  2061. msg, err := p.conn.receiveMessage()
  2062. if err != nil {
  2063. p.conn.asyncClose()
  2064. return nil, normalizeTimeoutError(p.ctx, err)
  2065. }
  2066. switch msg := msg.(type) {
  2067. case *pgproto3.ParameterDescription:
  2068. psd.ParamOIDs = make([]uint32, len(msg.ParameterOIDs))
  2069. copy(psd.ParamOIDs, msg.ParameterOIDs)
  2070. case *pgproto3.RowDescription:
  2071. psd.Fields = p.conn.convertRowDescription(nil, msg)
  2072. return psd, nil
  2073. // NoData is returned instead of RowDescription when there is no expected result. e.g. An INSERT without a RETURNING
  2074. // clause.
  2075. case *pgproto3.NoData:
  2076. return psd, nil
  2077. // These should never happen here. But don't take chances that could lead to a deadlock.
  2078. case *pgproto3.ErrorResponse:
  2079. pgErr := ErrorResponseToPgError(msg)
  2080. p.state.HandleError(pgErr)
  2081. return nil, pgErr
  2082. case *pgproto3.CommandComplete:
  2083. p.conn.asyncClose()
  2084. return nil, errors.New("BUG: received CommandComplete while handling Describe")
  2085. case *pgproto3.ReadyForQuery:
  2086. p.conn.asyncClose()
  2087. return nil, errors.New("BUG: received ReadyForQuery while handling Describe")
  2088. }
  2089. }
  2090. }
  2091. // Close closes the pipeline and returns the connection to normal mode.
  2092. func (p *Pipeline) Close() error {
  2093. if p.closed {
  2094. return p.err
  2095. }
  2096. p.closed = true
  2097. if p.state.PendingSync() {
  2098. p.conn.asyncClose()
  2099. p.err = errors.New("pipeline has unsynced requests")
  2100. p.conn.contextWatcher.Unwatch()
  2101. p.conn.unlock()
  2102. return p.err
  2103. }
  2104. for p.state.ExpectedReadyForQuery() > 0 {
  2105. _, err := p.getResults()
  2106. if err != nil {
  2107. p.err = err
  2108. var pgErr *PgError
  2109. if !errors.As(err, &pgErr) {
  2110. p.conn.asyncClose()
  2111. break
  2112. }
  2113. }
  2114. }
  2115. p.conn.contextWatcher.Unwatch()
  2116. p.conn.unlock()
  2117. return p.err
  2118. }
  2119. // DeadlineContextWatcherHandler handles canceled contexts by setting a deadline on a net.Conn.
  2120. type DeadlineContextWatcherHandler struct {
  2121. Conn net.Conn
  2122. // DeadlineDelay is the delay to set on the deadline set on net.Conn when the context is canceled.
  2123. DeadlineDelay time.Duration
  2124. }
  2125. func (h *DeadlineContextWatcherHandler) HandleCancel(ctx context.Context) {
  2126. h.Conn.SetDeadline(time.Now().Add(h.DeadlineDelay))
  2127. }
  2128. func (h *DeadlineContextWatcherHandler) HandleUnwatchAfterCancel() {
  2129. h.Conn.SetDeadline(time.Time{})
  2130. }
  2131. // CancelRequestContextWatcherHandler handles canceled contexts by sending a cancel request to the server. It also sets
  2132. // a deadline on a net.Conn as a fallback.
  2133. type CancelRequestContextWatcherHandler struct {
  2134. Conn *PgConn
  2135. // CancelRequestDelay is the delay before sending the cancel request to the server.
  2136. CancelRequestDelay time.Duration
  2137. // DeadlineDelay is the delay to set on the deadline set on net.Conn when the context is canceled.
  2138. DeadlineDelay time.Duration
  2139. cancelFinishedChan chan struct{}
  2140. handleUnwatchAfterCancelCalled func()
  2141. }
  2142. func (h *CancelRequestContextWatcherHandler) HandleCancel(context.Context) {
  2143. h.cancelFinishedChan = make(chan struct{})
  2144. var handleUnwatchedAfterCancelCalledCtx context.Context
  2145. handleUnwatchedAfterCancelCalledCtx, h.handleUnwatchAfterCancelCalled = context.WithCancel(context.Background())
  2146. deadline := time.Now().Add(h.DeadlineDelay)
  2147. h.Conn.conn.SetDeadline(deadline)
  2148. go func() {
  2149. defer close(h.cancelFinishedChan)
  2150. select {
  2151. case <-handleUnwatchedAfterCancelCalledCtx.Done():
  2152. return
  2153. case <-time.After(h.CancelRequestDelay):
  2154. }
  2155. cancelRequestCtx, cancel := context.WithDeadline(handleUnwatchedAfterCancelCalledCtx, deadline)
  2156. defer cancel()
  2157. h.Conn.CancelRequest(cancelRequestCtx)
  2158. // CancelRequest is inherently racy. Even though the cancel request has been received by the server at this point,
  2159. // it hasn't necessarily been delivered to the other connection. If we immediately return and the connection is
  2160. // immediately used then it is possible the CancelRequest will actually cancel our next query. The
  2161. // TestCancelRequestContextWatcherHandler Stress test can produce this error without the sleep below. The sleep time
  2162. // is arbitrary, but should be sufficient to prevent this error case.
  2163. time.Sleep(100 * time.Millisecond)
  2164. }()
  2165. }
  2166. func (h *CancelRequestContextWatcherHandler) HandleUnwatchAfterCancel() {
  2167. h.handleUnwatchAfterCancelCalled()
  2168. <-h.cancelFinishedChan
  2169. h.Conn.conn.SetDeadline(time.Time{})
  2170. }