conn.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778
  1. package pq
  2. import (
  3. "bufio"
  4. "crypto/md5"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "database/sql"
  8. "database/sql/driver"
  9. "encoding/binary"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "io/ioutil"
  14. "net"
  15. "os"
  16. "os/user"
  17. "path"
  18. "path/filepath"
  19. "strconv"
  20. "strings"
  21. "time"
  22. "unicode"
  23. "github.com/lib/pq/oid"
  24. )
  25. // Common error types
  26. var (
  27. ErrNotSupported = errors.New("pq: Unsupported command")
  28. ErrInFailedTransaction = errors.New("pq: Could not complete operation in a failed transaction")
  29. ErrSSLNotSupported = errors.New("pq: SSL is not enabled on the server")
  30. ErrSSLKeyHasWorldPermissions = errors.New("pq: Private key file has group or world access. Permissions should be u=rw (0600) or less.")
  31. ErrCouldNotDetectUsername = errors.New("pq: Could not detect default username. Please provide one explicitly.")
  32. )
  33. type drv struct{}
  34. func (d *drv) Open(name string) (driver.Conn, error) {
  35. return Open(name)
  36. }
  37. func init() {
  38. sql.Register("postgres", &drv{})
  39. }
  40. type parameterStatus struct {
  41. // server version in the same format as server_version_num, or 0 if
  42. // unavailable
  43. serverVersion int
  44. // the current location based on the TimeZone value of the session, if
  45. // available
  46. currentLocation *time.Location
  47. }
  48. type transactionStatus byte
  49. const (
  50. txnStatusIdle transactionStatus = 'I'
  51. txnStatusIdleInTransaction transactionStatus = 'T'
  52. txnStatusInFailedTransaction transactionStatus = 'E'
  53. )
  54. func (s transactionStatus) String() string {
  55. switch s {
  56. case txnStatusIdle:
  57. return "idle"
  58. case txnStatusIdleInTransaction:
  59. return "idle in transaction"
  60. case txnStatusInFailedTransaction:
  61. return "in a failed transaction"
  62. default:
  63. errorf("unknown transactionStatus %d", s)
  64. }
  65. panic("not reached")
  66. }
  67. type Dialer interface {
  68. Dial(network, address string) (net.Conn, error)
  69. DialTimeout(network, address string, timeout time.Duration) (net.Conn, error)
  70. }
  71. type defaultDialer struct{}
  72. func (d defaultDialer) Dial(ntw, addr string) (net.Conn, error) {
  73. return net.Dial(ntw, addr)
  74. }
  75. func (d defaultDialer) DialTimeout(ntw, addr string, timeout time.Duration) (net.Conn, error) {
  76. return net.DialTimeout(ntw, addr, timeout)
  77. }
  78. type conn struct {
  79. c net.Conn
  80. buf *bufio.Reader
  81. namei int
  82. scratch [512]byte
  83. txnStatus transactionStatus
  84. parameterStatus parameterStatus
  85. saveMessageType byte
  86. saveMessageBuffer []byte
  87. // If true, this connection is bad and all public-facing functions should
  88. // return ErrBadConn.
  89. bad bool
  90. // If set, this connection should never use the binary format when
  91. // receiving query results from prepared statements. Only provided for
  92. // debugging.
  93. disablePreparedBinaryResult bool
  94. // Whether to always send []byte parameters over as binary. Enables single
  95. // round-trip mode for non-prepared Query calls.
  96. binaryParameters bool
  97. }
  98. // Handle driver-side settings in parsed connection string.
  99. func (c *conn) handleDriverSettings(o values) (err error) {
  100. boolSetting := func(key string, val *bool) error {
  101. if value := o.Get(key); value != "" {
  102. if value == "yes" {
  103. *val = true
  104. } else if value == "no" {
  105. *val = false
  106. } else {
  107. return fmt.Errorf("unrecognized value %q for %s", value, key)
  108. }
  109. }
  110. return nil
  111. }
  112. err = boolSetting("disable_prepared_binary_result", &c.disablePreparedBinaryResult)
  113. if err != nil {
  114. return err
  115. }
  116. err = boolSetting("binary_parameters", &c.binaryParameters)
  117. if err != nil {
  118. return err
  119. }
  120. return nil
  121. }
  122. func (c *conn) writeBuf(b byte) *writeBuf {
  123. c.scratch[0] = b
  124. return &writeBuf{
  125. buf: c.scratch[:5],
  126. pos: 1,
  127. }
  128. }
  129. func Open(name string) (_ driver.Conn, err error) {
  130. return DialOpen(defaultDialer{}, name)
  131. }
  132. func DialOpen(d Dialer, name string) (_ driver.Conn, err error) {
  133. // Handle any panics during connection initialization. Note that we
  134. // specifically do *not* want to use errRecover(), as that would turn any
  135. // connection errors into ErrBadConns, hiding the real error message from
  136. // the user.
  137. defer errRecoverNoErrBadConn(&err)
  138. o := make(values)
  139. // A number of defaults are applied here, in this order:
  140. //
  141. // * Very low precedence defaults applied in every situation
  142. // * Environment variables
  143. // * Explicitly passed connection information
  144. o.Set("host", "localhost")
  145. o.Set("port", "5432")
  146. // N.B.: Extra float digits should be set to 3, but that breaks
  147. // Postgres 8.4 and older, where the max is 2.
  148. o.Set("extra_float_digits", "2")
  149. for k, v := range parseEnviron(os.Environ()) {
  150. o.Set(k, v)
  151. }
  152. if strings.HasPrefix(name, "postgres://") || strings.HasPrefix(name, "postgresql://") {
  153. name, err = ParseURL(name)
  154. if err != nil {
  155. return nil, err
  156. }
  157. }
  158. if err := parseOpts(name, o); err != nil {
  159. return nil, err
  160. }
  161. // Use the "fallback" application name if necessary
  162. if fallback := o.Get("fallback_application_name"); fallback != "" {
  163. if !o.Isset("application_name") {
  164. o.Set("application_name", fallback)
  165. }
  166. }
  167. // We can't work with any client_encoding other than UTF-8 currently.
  168. // However, we have historically allowed the user to set it to UTF-8
  169. // explicitly, and there's no reason to break such programs, so allow that.
  170. // Note that the "options" setting could also set client_encoding, but
  171. // parsing its value is not worth it. Instead, we always explicitly send
  172. // client_encoding as a separate run-time parameter, which should override
  173. // anything set in options.
  174. if enc := o.Get("client_encoding"); enc != "" && !isUTF8(enc) {
  175. return nil, errors.New("client_encoding must be absent or 'UTF8'")
  176. }
  177. o.Set("client_encoding", "UTF8")
  178. // DateStyle needs a similar treatment.
  179. if datestyle := o.Get("datestyle"); datestyle != "" {
  180. if datestyle != "ISO, MDY" {
  181. panic(fmt.Sprintf("setting datestyle must be absent or %v; got %v",
  182. "ISO, MDY", datestyle))
  183. }
  184. } else {
  185. o.Set("datestyle", "ISO, MDY")
  186. }
  187. // If a user is not provided by any other means, the last
  188. // resort is to use the current operating system provided user
  189. // name.
  190. if o.Get("user") == "" {
  191. u, err := userCurrent()
  192. if err != nil {
  193. return nil, err
  194. } else {
  195. o.Set("user", u)
  196. }
  197. }
  198. cn := &conn{}
  199. err = cn.handleDriverSettings(o)
  200. if err != nil {
  201. return nil, err
  202. }
  203. cn.c, err = dial(d, o)
  204. if err != nil {
  205. return nil, err
  206. }
  207. cn.ssl(o)
  208. cn.buf = bufio.NewReader(cn.c)
  209. cn.startup(o)
  210. // reset the deadline, in case one was set (see dial)
  211. if timeout := o.Get("connect_timeout"); timeout != "" && timeout != "0" {
  212. err = cn.c.SetDeadline(time.Time{})
  213. }
  214. return cn, err
  215. }
  216. func dial(d Dialer, o values) (net.Conn, error) {
  217. ntw, addr := network(o)
  218. // SSL is not necessary or supported over UNIX domain sockets
  219. if ntw == "unix" {
  220. o["sslmode"] = "disable"
  221. }
  222. // Zero or not specified means wait indefinitely.
  223. if timeout := o.Get("connect_timeout"); timeout != "" && timeout != "0" {
  224. seconds, err := strconv.ParseInt(timeout, 10, 0)
  225. if err != nil {
  226. return nil, fmt.Errorf("invalid value for parameter connect_timeout: %s", err)
  227. }
  228. duration := time.Duration(seconds) * time.Second
  229. // connect_timeout should apply to the entire connection establishment
  230. // procedure, so we both use a timeout for the TCP connection
  231. // establishment and set a deadline for doing the initial handshake.
  232. // The deadline is then reset after startup() is done.
  233. deadline := time.Now().Add(duration)
  234. conn, err := d.DialTimeout(ntw, addr, duration)
  235. if err != nil {
  236. return nil, err
  237. }
  238. err = conn.SetDeadline(deadline)
  239. return conn, err
  240. }
  241. return d.Dial(ntw, addr)
  242. }
  243. func network(o values) (string, string) {
  244. host := o.Get("host")
  245. if strings.HasPrefix(host, "/") {
  246. sockPath := path.Join(host, ".s.PGSQL."+o.Get("port"))
  247. return "unix", sockPath
  248. }
  249. return "tcp", host + ":" + o.Get("port")
  250. }
  251. type values map[string]string
  252. func (vs values) Set(k, v string) {
  253. vs[k] = v
  254. }
  255. func (vs values) Get(k string) (v string) {
  256. return vs[k]
  257. }
  258. func (vs values) Isset(k string) bool {
  259. _, ok := vs[k]
  260. return ok
  261. }
  262. // scanner implements a tokenizer for libpq-style option strings.
  263. type scanner struct {
  264. s []rune
  265. i int
  266. }
  267. // newScanner returns a new scanner initialized with the option string s.
  268. func newScanner(s string) *scanner {
  269. return &scanner{[]rune(s), 0}
  270. }
  271. // Next returns the next rune.
  272. // It returns 0, false if the end of the text has been reached.
  273. func (s *scanner) Next() (rune, bool) {
  274. if s.i >= len(s.s) {
  275. return 0, false
  276. }
  277. r := s.s[s.i]
  278. s.i++
  279. return r, true
  280. }
  281. // SkipSpaces returns the next non-whitespace rune.
  282. // It returns 0, false if the end of the text has been reached.
  283. func (s *scanner) SkipSpaces() (rune, bool) {
  284. r, ok := s.Next()
  285. for unicode.IsSpace(r) && ok {
  286. r, ok = s.Next()
  287. }
  288. return r, ok
  289. }
  290. // parseOpts parses the options from name and adds them to the values.
  291. //
  292. // The parsing code is based on conninfo_parse from libpq's fe-connect.c
  293. func parseOpts(name string, o values) error {
  294. s := newScanner(name)
  295. for {
  296. var (
  297. keyRunes, valRunes []rune
  298. r rune
  299. ok bool
  300. )
  301. if r, ok = s.SkipSpaces(); !ok {
  302. break
  303. }
  304. // Scan the key
  305. for !unicode.IsSpace(r) && r != '=' {
  306. keyRunes = append(keyRunes, r)
  307. if r, ok = s.Next(); !ok {
  308. break
  309. }
  310. }
  311. // Skip any whitespace if we're not at the = yet
  312. if r != '=' {
  313. r, ok = s.SkipSpaces()
  314. }
  315. // The current character should be =
  316. if r != '=' || !ok {
  317. return fmt.Errorf(`missing "=" after %q in connection info string"`, string(keyRunes))
  318. }
  319. // Skip any whitespace after the =
  320. if r, ok = s.SkipSpaces(); !ok {
  321. // If we reach the end here, the last value is just an empty string as per libpq.
  322. o.Set(string(keyRunes), "")
  323. break
  324. }
  325. if r != '\'' {
  326. for !unicode.IsSpace(r) {
  327. if r == '\\' {
  328. if r, ok = s.Next(); !ok {
  329. return fmt.Errorf(`missing character after backslash`)
  330. }
  331. }
  332. valRunes = append(valRunes, r)
  333. if r, ok = s.Next(); !ok {
  334. break
  335. }
  336. }
  337. } else {
  338. quote:
  339. for {
  340. if r, ok = s.Next(); !ok {
  341. return fmt.Errorf(`unterminated quoted string literal in connection string`)
  342. }
  343. switch r {
  344. case '\'':
  345. break quote
  346. case '\\':
  347. r, _ = s.Next()
  348. fallthrough
  349. default:
  350. valRunes = append(valRunes, r)
  351. }
  352. }
  353. }
  354. o.Set(string(keyRunes), string(valRunes))
  355. }
  356. return nil
  357. }
  358. func (cn *conn) isInTransaction() bool {
  359. return cn.txnStatus == txnStatusIdleInTransaction ||
  360. cn.txnStatus == txnStatusInFailedTransaction
  361. }
  362. func (cn *conn) checkIsInTransaction(intxn bool) {
  363. if cn.isInTransaction() != intxn {
  364. cn.bad = true
  365. errorf("unexpected transaction status %v", cn.txnStatus)
  366. }
  367. }
  368. func (cn *conn) Begin() (_ driver.Tx, err error) {
  369. if cn.bad {
  370. return nil, driver.ErrBadConn
  371. }
  372. defer cn.errRecover(&err)
  373. cn.checkIsInTransaction(false)
  374. _, commandTag, err := cn.simpleExec("BEGIN")
  375. if err != nil {
  376. return nil, err
  377. }
  378. if commandTag != "BEGIN" {
  379. cn.bad = true
  380. return nil, fmt.Errorf("unexpected command tag %s", commandTag)
  381. }
  382. if cn.txnStatus != txnStatusIdleInTransaction {
  383. cn.bad = true
  384. return nil, fmt.Errorf("unexpected transaction status %v", cn.txnStatus)
  385. }
  386. return cn, nil
  387. }
  388. func (cn *conn) Commit() (err error) {
  389. if cn.bad {
  390. return driver.ErrBadConn
  391. }
  392. defer cn.errRecover(&err)
  393. cn.checkIsInTransaction(true)
  394. // We don't want the client to think that everything is okay if it tries
  395. // to commit a failed transaction. However, no matter what we return,
  396. // database/sql will release this connection back into the free connection
  397. // pool so we have to abort the current transaction here. Note that you
  398. // would get the same behaviour if you issued a COMMIT in a failed
  399. // transaction, so it's also the least surprising thing to do here.
  400. if cn.txnStatus == txnStatusInFailedTransaction {
  401. if err := cn.Rollback(); err != nil {
  402. return err
  403. }
  404. return ErrInFailedTransaction
  405. }
  406. _, commandTag, err := cn.simpleExec("COMMIT")
  407. if err != nil {
  408. if cn.isInTransaction() {
  409. cn.bad = true
  410. }
  411. return err
  412. }
  413. if commandTag != "COMMIT" {
  414. cn.bad = true
  415. return fmt.Errorf("unexpected command tag %s", commandTag)
  416. }
  417. cn.checkIsInTransaction(false)
  418. return nil
  419. }
  420. func (cn *conn) Rollback() (err error) {
  421. if cn.bad {
  422. return driver.ErrBadConn
  423. }
  424. defer cn.errRecover(&err)
  425. cn.checkIsInTransaction(true)
  426. _, commandTag, err := cn.simpleExec("ROLLBACK")
  427. if err != nil {
  428. if cn.isInTransaction() {
  429. cn.bad = true
  430. }
  431. return err
  432. }
  433. if commandTag != "ROLLBACK" {
  434. return fmt.Errorf("unexpected command tag %s", commandTag)
  435. }
  436. cn.checkIsInTransaction(false)
  437. return nil
  438. }
  439. func (cn *conn) gname() string {
  440. cn.namei++
  441. return strconv.FormatInt(int64(cn.namei), 10)
  442. }
  443. func (cn *conn) simpleExec(q string) (res driver.Result, commandTag string, err error) {
  444. b := cn.writeBuf('Q')
  445. b.string(q)
  446. cn.send(b)
  447. for {
  448. t, r := cn.recv1()
  449. switch t {
  450. case 'C':
  451. res, commandTag = cn.parseComplete(r.string())
  452. case 'Z':
  453. cn.processReadyForQuery(r)
  454. // done
  455. return
  456. case 'E':
  457. err = parseError(r)
  458. case 'T', 'D', 'I':
  459. // ignore any results
  460. default:
  461. cn.bad = true
  462. errorf("unknown response for simple query: %q", t)
  463. }
  464. }
  465. }
  466. func (cn *conn) simpleQuery(q string) (res *rows, err error) {
  467. defer cn.errRecover(&err)
  468. st := &stmt{cn: cn, name: ""}
  469. b := cn.writeBuf('Q')
  470. b.string(q)
  471. cn.send(b)
  472. for {
  473. t, r := cn.recv1()
  474. switch t {
  475. case 'C', 'I':
  476. // We allow queries which don't return any results through Query as
  477. // well as Exec. We still have to give database/sql a rows object
  478. // the user can close, though, to avoid connections from being
  479. // leaked. A "rows" with done=true works fine for that purpose.
  480. if err != nil {
  481. cn.bad = true
  482. errorf("unexpected message %q in simple query execution", t)
  483. }
  484. if res == nil {
  485. res = &rows{
  486. cn: cn,
  487. colNames: st.colNames,
  488. colTyps: st.colTyps,
  489. colFmts: st.colFmts,
  490. }
  491. }
  492. res.done = true
  493. case 'Z':
  494. cn.processReadyForQuery(r)
  495. // done
  496. return
  497. case 'E':
  498. res = nil
  499. err = parseError(r)
  500. case 'D':
  501. if res == nil {
  502. cn.bad = true
  503. errorf("unexpected DataRow in simple query execution")
  504. }
  505. // the query didn't fail; kick off to Next
  506. cn.saveMessage(t, r)
  507. return
  508. case 'T':
  509. // res might be non-nil here if we received a previous
  510. // CommandComplete, but that's fine; just overwrite it
  511. res = &rows{cn: cn}
  512. res.colNames, res.colFmts, res.colTyps = parsePortalRowDescribe(r)
  513. // To work around a bug in QueryRow in Go 1.2 and earlier, wait
  514. // until the first DataRow has been received.
  515. default:
  516. cn.bad = true
  517. errorf("unknown response for simple query: %q", t)
  518. }
  519. }
  520. }
  521. // Decides which column formats to use for a prepared statement. The input is
  522. // an array of type oids, one element per result column.
  523. func decideColumnFormats(colTyps []oid.Oid, forceText bool) (colFmts []format, colFmtData []byte) {
  524. if len(colTyps) == 0 {
  525. return nil, colFmtDataAllText
  526. }
  527. colFmts = make([]format, len(colTyps))
  528. if forceText {
  529. return colFmts, colFmtDataAllText
  530. }
  531. allBinary := true
  532. allText := true
  533. for i, o := range colTyps {
  534. switch o {
  535. // This is the list of types to use binary mode for when receiving them
  536. // through a prepared statement. If a type appears in this list, it
  537. // must also be implemented in binaryDecode in encode.go.
  538. case oid.T_bytea:
  539. fallthrough
  540. case oid.T_int8:
  541. fallthrough
  542. case oid.T_int4:
  543. fallthrough
  544. case oid.T_int2:
  545. colFmts[i] = formatBinary
  546. allText = false
  547. default:
  548. allBinary = false
  549. }
  550. }
  551. if allBinary {
  552. return colFmts, colFmtDataAllBinary
  553. } else if allText {
  554. return colFmts, colFmtDataAllText
  555. } else {
  556. colFmtData = make([]byte, 2+len(colFmts)*2)
  557. binary.BigEndian.PutUint16(colFmtData, uint16(len(colFmts)))
  558. for i, v := range colFmts {
  559. binary.BigEndian.PutUint16(colFmtData[2+i*2:], uint16(v))
  560. }
  561. return colFmts, colFmtData
  562. }
  563. }
  564. func (cn *conn) prepareTo(q, stmtName string) *stmt {
  565. st := &stmt{cn: cn, name: stmtName}
  566. b := cn.writeBuf('P')
  567. b.string(st.name)
  568. b.string(q)
  569. b.int16(0)
  570. b.next('D')
  571. b.byte('S')
  572. b.string(st.name)
  573. b.next('S')
  574. cn.send(b)
  575. cn.readParseResponse()
  576. st.paramTyps, st.colNames, st.colTyps = cn.readStatementDescribeResponse()
  577. st.colFmts, st.colFmtData = decideColumnFormats(st.colTyps, cn.disablePreparedBinaryResult)
  578. cn.readReadyForQuery()
  579. return st
  580. }
  581. func (cn *conn) Prepare(q string) (_ driver.Stmt, err error) {
  582. if cn.bad {
  583. return nil, driver.ErrBadConn
  584. }
  585. defer cn.errRecover(&err)
  586. if len(q) >= 4 && strings.EqualFold(q[:4], "COPY") {
  587. return cn.prepareCopyIn(q)
  588. }
  589. return cn.prepareTo(q, cn.gname()), nil
  590. }
  591. func (cn *conn) Close() (err error) {
  592. if cn.bad {
  593. return driver.ErrBadConn
  594. }
  595. defer cn.errRecover(&err)
  596. // Don't go through send(); ListenerConn relies on us not scribbling on the
  597. // scratch buffer of this connection.
  598. err = cn.sendSimpleMessage('X')
  599. if err != nil {
  600. return err
  601. }
  602. return cn.c.Close()
  603. }
  604. // Implement the "Queryer" interface
  605. func (cn *conn) Query(query string, args []driver.Value) (_ driver.Rows, err error) {
  606. if cn.bad {
  607. return nil, driver.ErrBadConn
  608. }
  609. defer cn.errRecover(&err)
  610. // Check to see if we can use the "simpleQuery" interface, which is
  611. // *much* faster than going through prepare/exec
  612. if len(args) == 0 {
  613. return cn.simpleQuery(query)
  614. }
  615. if cn.binaryParameters {
  616. cn.sendBinaryModeQuery(query, args)
  617. cn.readParseResponse()
  618. cn.readBindResponse()
  619. rows := &rows{cn: cn}
  620. rows.colNames, rows.colFmts, rows.colTyps = cn.readPortalDescribeResponse()
  621. cn.postExecuteWorkaround()
  622. return rows, nil
  623. } else {
  624. st := cn.prepareTo(query, "")
  625. st.exec(args)
  626. return &rows{
  627. cn: cn,
  628. colNames: st.colNames,
  629. colTyps: st.colTyps,
  630. colFmts: st.colFmts,
  631. }, nil
  632. }
  633. }
  634. // Implement the optional "Execer" interface for one-shot queries
  635. func (cn *conn) Exec(query string, args []driver.Value) (res driver.Result, err error) {
  636. if cn.bad {
  637. return nil, driver.ErrBadConn
  638. }
  639. defer cn.errRecover(&err)
  640. // Check to see if we can use the "simpleExec" interface, which is
  641. // *much* faster than going through prepare/exec
  642. if len(args) == 0 {
  643. // ignore commandTag, our caller doesn't care
  644. r, _, err := cn.simpleExec(query)
  645. return r, err
  646. }
  647. if cn.binaryParameters {
  648. cn.sendBinaryModeQuery(query, args)
  649. cn.readParseResponse()
  650. cn.readBindResponse()
  651. cn.readPortalDescribeResponse()
  652. cn.postExecuteWorkaround()
  653. res, _, err = cn.readExecuteResponse("Execute")
  654. return res, err
  655. } else {
  656. // Use the unnamed statement to defer planning until bind
  657. // time, or else value-based selectivity estimates cannot be
  658. // used.
  659. st := cn.prepareTo(query, "")
  660. r, err := st.Exec(args)
  661. if err != nil {
  662. panic(err)
  663. }
  664. return r, err
  665. }
  666. }
  667. func (cn *conn) send(m *writeBuf) {
  668. _, err := cn.c.Write(m.wrap())
  669. if err != nil {
  670. panic(err)
  671. }
  672. }
  673. func (cn *conn) sendStartupPacket(m *writeBuf) {
  674. // sanity check
  675. if m.buf[0] != 0 {
  676. panic("oops")
  677. }
  678. _, err := cn.c.Write((m.wrap())[1:])
  679. if err != nil {
  680. panic(err)
  681. }
  682. }
  683. // Send a message of type typ to the server on the other end of cn. The
  684. // message should have no payload. This method does not use the scratch
  685. // buffer.
  686. func (cn *conn) sendSimpleMessage(typ byte) (err error) {
  687. _, err = cn.c.Write([]byte{typ, '\x00', '\x00', '\x00', '\x04'})
  688. return err
  689. }
  690. // saveMessage memorizes a message and its buffer in the conn struct.
  691. // recvMessage will then return these values on the next call to it. This
  692. // method is useful in cases where you have to see what the next message is
  693. // going to be (e.g. to see whether it's an error or not) but you can't handle
  694. // the message yourself.
  695. func (cn *conn) saveMessage(typ byte, buf *readBuf) {
  696. if cn.saveMessageType != 0 {
  697. cn.bad = true
  698. errorf("unexpected saveMessageType %d", cn.saveMessageType)
  699. }
  700. cn.saveMessageType = typ
  701. cn.saveMessageBuffer = *buf
  702. }
  703. // recvMessage receives any message from the backend, or returns an error if
  704. // a problem occurred while reading the message.
  705. func (cn *conn) recvMessage(r *readBuf) (byte, error) {
  706. // workaround for a QueryRow bug, see exec
  707. if cn.saveMessageType != 0 {
  708. t := cn.saveMessageType
  709. *r = cn.saveMessageBuffer
  710. cn.saveMessageType = 0
  711. cn.saveMessageBuffer = nil
  712. return t, nil
  713. }
  714. x := cn.scratch[:5]
  715. _, err := io.ReadFull(cn.buf, x)
  716. if err != nil {
  717. return 0, err
  718. }
  719. // read the type and length of the message that follows
  720. t := x[0]
  721. n := int(binary.BigEndian.Uint32(x[1:])) - 4
  722. var y []byte
  723. if n <= len(cn.scratch) {
  724. y = cn.scratch[:n]
  725. } else {
  726. y = make([]byte, n)
  727. }
  728. _, err = io.ReadFull(cn.buf, y)
  729. if err != nil {
  730. return 0, err
  731. }
  732. *r = y
  733. return t, nil
  734. }
  735. // recv receives a message from the backend, but if an error happened while
  736. // reading the message or the received message was an ErrorResponse, it panics.
  737. // NoticeResponses are ignored. This function should generally be used only
  738. // during the startup sequence.
  739. func (cn *conn) recv() (t byte, r *readBuf) {
  740. for {
  741. var err error
  742. r = &readBuf{}
  743. t, err = cn.recvMessage(r)
  744. if err != nil {
  745. panic(err)
  746. }
  747. switch t {
  748. case 'E':
  749. panic(parseError(r))
  750. case 'N':
  751. // ignore
  752. default:
  753. return
  754. }
  755. }
  756. }
  757. // recv1Buf is exactly equivalent to recv1, except it uses a buffer supplied by
  758. // the caller to avoid an allocation.
  759. func (cn *conn) recv1Buf(r *readBuf) byte {
  760. for {
  761. t, err := cn.recvMessage(r)
  762. if err != nil {
  763. panic(err)
  764. }
  765. switch t {
  766. case 'A', 'N':
  767. // ignore
  768. case 'S':
  769. cn.processParameterStatus(r)
  770. default:
  771. return t
  772. }
  773. }
  774. }
  775. // recv1 receives a message from the backend, panicking if an error occurs
  776. // while attempting to read it. All asynchronous messages are ignored, with
  777. // the exception of ErrorResponse.
  778. func (cn *conn) recv1() (t byte, r *readBuf) {
  779. r = &readBuf{}
  780. t = cn.recv1Buf(r)
  781. return t, r
  782. }
  783. func (cn *conn) ssl(o values) {
  784. verifyCaOnly := false
  785. tlsConf := tls.Config{}
  786. switch mode := o.Get("sslmode"); mode {
  787. case "require", "":
  788. tlsConf.InsecureSkipVerify = true
  789. case "verify-ca":
  790. // We must skip TLS's own verification since it requires full
  791. // verification since Go 1.3.
  792. tlsConf.InsecureSkipVerify = true
  793. verifyCaOnly = true
  794. case "verify-full":
  795. tlsConf.ServerName = o.Get("host")
  796. case "disable":
  797. return
  798. default:
  799. errorf(`unsupported sslmode %q; only "require" (default), "verify-full", and "disable" supported`, mode)
  800. }
  801. cn.setupSSLClientCertificates(&tlsConf, o)
  802. cn.setupSSLCA(&tlsConf, o)
  803. w := cn.writeBuf(0)
  804. w.int32(80877103)
  805. cn.sendStartupPacket(w)
  806. b := cn.scratch[:1]
  807. _, err := io.ReadFull(cn.c, b)
  808. if err != nil {
  809. panic(err)
  810. }
  811. if b[0] != 'S' {
  812. panic(ErrSSLNotSupported)
  813. }
  814. client := tls.Client(cn.c, &tlsConf)
  815. if verifyCaOnly {
  816. cn.verifyCA(client, &tlsConf)
  817. }
  818. cn.c = client
  819. }
  820. // verifyCA carries out a TLS handshake to the server and verifies the
  821. // presented certificate against the effective CA, i.e. the one specified in
  822. // sslrootcert or the system CA if sslrootcert was not specified.
  823. func (cn *conn) verifyCA(client *tls.Conn, tlsConf *tls.Config) {
  824. err := client.Handshake()
  825. if err != nil {
  826. panic(err)
  827. }
  828. certs := client.ConnectionState().PeerCertificates
  829. opts := x509.VerifyOptions{
  830. DNSName: client.ConnectionState().ServerName,
  831. Intermediates: x509.NewCertPool(),
  832. Roots: tlsConf.RootCAs,
  833. }
  834. for i, cert := range certs {
  835. if i == 0 {
  836. continue
  837. }
  838. opts.Intermediates.AddCert(cert)
  839. }
  840. _, err = certs[0].Verify(opts)
  841. if err != nil {
  842. panic(err)
  843. }
  844. }
  845. // This function sets up SSL client certificates based on either the "sslkey"
  846. // and "sslcert" settings (possibly set via the environment variables PGSSLKEY
  847. // and PGSSLCERT, respectively), or if they aren't set, from the .postgresql
  848. // directory in the user's home directory. If the file paths are set
  849. // explicitly, the files must exist. The key file must also not be
  850. // world-readable, or this function will panic with
  851. // ErrSSLKeyHasWorldPermissions.
  852. func (cn *conn) setupSSLClientCertificates(tlsConf *tls.Config, o values) {
  853. var missingOk bool
  854. sslkey := o.Get("sslkey")
  855. sslcert := o.Get("sslcert")
  856. if sslkey != "" && sslcert != "" {
  857. // If the user has set an sslkey and sslcert, they *must* exist.
  858. missingOk = false
  859. } else {
  860. // Automatically load certificates from ~/.postgresql.
  861. user, err := user.Current()
  862. if err != nil {
  863. // user.Current() might fail when cross-compiling. We have to
  864. // ignore the error and continue without client certificates, since
  865. // we wouldn't know where to load them from.
  866. return
  867. }
  868. sslkey = filepath.Join(user.HomeDir, ".postgresql", "postgresql.key")
  869. sslcert = filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt")
  870. missingOk = true
  871. }
  872. // Check that both files exist, and report the error or stop, depending on
  873. // which behaviour we want. Note that we don't do any more extensive
  874. // checks than this (such as checking that the paths aren't directories);
  875. // LoadX509KeyPair() will take care of the rest.
  876. keyfinfo, err := os.Stat(sslkey)
  877. if err != nil && missingOk {
  878. return
  879. } else if err != nil {
  880. panic(err)
  881. }
  882. _, err = os.Stat(sslcert)
  883. if err != nil && missingOk {
  884. return
  885. } else if err != nil {
  886. panic(err)
  887. }
  888. // If we got this far, the key file must also have the correct permissions
  889. kmode := keyfinfo.Mode()
  890. if kmode != kmode&0600 {
  891. panic(ErrSSLKeyHasWorldPermissions)
  892. }
  893. cert, err := tls.LoadX509KeyPair(sslcert, sslkey)
  894. if err != nil {
  895. panic(err)
  896. }
  897. tlsConf.Certificates = []tls.Certificate{cert}
  898. }
  899. // Sets up RootCAs in the TLS configuration if sslrootcert is set.
  900. func (cn *conn) setupSSLCA(tlsConf *tls.Config, o values) {
  901. if sslrootcert := o.Get("sslrootcert"); sslrootcert != "" {
  902. tlsConf.RootCAs = x509.NewCertPool()
  903. cert, err := ioutil.ReadFile(sslrootcert)
  904. if err != nil {
  905. panic(err)
  906. }
  907. ok := tlsConf.RootCAs.AppendCertsFromPEM(cert)
  908. if !ok {
  909. errorf("couldn't parse pem in sslrootcert")
  910. }
  911. }
  912. }
  913. // isDriverSetting returns true iff a setting is purely for configuring the
  914. // driver's options and should not be sent to the server in the connection
  915. // startup packet.
  916. func isDriverSetting(key string) bool {
  917. switch key {
  918. case "host", "port":
  919. return true
  920. case "password":
  921. return true
  922. case "sslmode", "sslcert", "sslkey", "sslrootcert":
  923. return true
  924. case "fallback_application_name":
  925. return true
  926. case "connect_timeout":
  927. return true
  928. case "disable_prepared_binary_result":
  929. return true
  930. case "binary_parameters":
  931. return true
  932. default:
  933. return false
  934. }
  935. }
  936. func (cn *conn) startup(o values) {
  937. w := cn.writeBuf(0)
  938. w.int32(196608)
  939. // Send the backend the name of the database we want to connect to, and the
  940. // user we want to connect as. Additionally, we send over any run-time
  941. // parameters potentially included in the connection string. If the server
  942. // doesn't recognize any of them, it will reply with an error.
  943. for k, v := range o {
  944. if isDriverSetting(k) {
  945. // skip options which can't be run-time parameters
  946. continue
  947. }
  948. // The protocol requires us to supply the database name as "database"
  949. // instead of "dbname".
  950. if k == "dbname" {
  951. k = "database"
  952. }
  953. w.string(k)
  954. w.string(v)
  955. }
  956. w.string("")
  957. cn.sendStartupPacket(w)
  958. for {
  959. t, r := cn.recv()
  960. switch t {
  961. case 'K':
  962. case 'S':
  963. cn.processParameterStatus(r)
  964. case 'R':
  965. cn.auth(r, o)
  966. case 'Z':
  967. cn.processReadyForQuery(r)
  968. return
  969. default:
  970. errorf("unknown response for startup: %q", t)
  971. }
  972. }
  973. }
  974. func (cn *conn) auth(r *readBuf, o values) {
  975. switch code := r.int32(); code {
  976. case 0:
  977. // OK
  978. case 3:
  979. w := cn.writeBuf('p')
  980. w.string(o.Get("password"))
  981. cn.send(w)
  982. t, r := cn.recv()
  983. if t != 'R' {
  984. errorf("unexpected password response: %q", t)
  985. }
  986. if r.int32() != 0 {
  987. errorf("unexpected authentication response: %q", t)
  988. }
  989. case 5:
  990. s := string(r.next(4))
  991. w := cn.writeBuf('p')
  992. w.string("md5" + md5s(md5s(o.Get("password")+o.Get("user"))+s))
  993. cn.send(w)
  994. t, r := cn.recv()
  995. if t != 'R' {
  996. errorf("unexpected password response: %q", t)
  997. }
  998. if r.int32() != 0 {
  999. errorf("unexpected authentication response: %q", t)
  1000. }
  1001. default:
  1002. errorf("unknown authentication response: %d", code)
  1003. }
  1004. }
  1005. type format int
  1006. const formatText format = 0
  1007. const formatBinary format = 1
  1008. // One result-column format code with the value 1 (i.e. all binary).
  1009. var colFmtDataAllBinary []byte = []byte{0, 1, 0, 1}
  1010. // No result-column format codes (i.e. all text).
  1011. var colFmtDataAllText []byte = []byte{0, 0}
  1012. type stmt struct {
  1013. cn *conn
  1014. name string
  1015. colNames []string
  1016. colFmts []format
  1017. colFmtData []byte
  1018. colTyps []oid.Oid
  1019. paramTyps []oid.Oid
  1020. closed bool
  1021. }
  1022. func (st *stmt) Close() (err error) {
  1023. if st.closed {
  1024. return nil
  1025. }
  1026. if st.cn.bad {
  1027. return driver.ErrBadConn
  1028. }
  1029. defer st.cn.errRecover(&err)
  1030. w := st.cn.writeBuf('C')
  1031. w.byte('S')
  1032. w.string(st.name)
  1033. st.cn.send(w)
  1034. st.cn.send(st.cn.writeBuf('S'))
  1035. t, _ := st.cn.recv1()
  1036. if t != '3' {
  1037. st.cn.bad = true
  1038. errorf("unexpected close response: %q", t)
  1039. }
  1040. st.closed = true
  1041. t, r := st.cn.recv1()
  1042. if t != 'Z' {
  1043. st.cn.bad = true
  1044. errorf("expected ready for query, but got: %q", t)
  1045. }
  1046. st.cn.processReadyForQuery(r)
  1047. return nil
  1048. }
  1049. func (st *stmt) Query(v []driver.Value) (r driver.Rows, err error) {
  1050. if st.cn.bad {
  1051. return nil, driver.ErrBadConn
  1052. }
  1053. defer st.cn.errRecover(&err)
  1054. st.exec(v)
  1055. return &rows{
  1056. cn: st.cn,
  1057. colNames: st.colNames,
  1058. colTyps: st.colTyps,
  1059. colFmts: st.colFmts,
  1060. }, nil
  1061. }
  1062. func (st *stmt) Exec(v []driver.Value) (res driver.Result, err error) {
  1063. if st.cn.bad {
  1064. return nil, driver.ErrBadConn
  1065. }
  1066. defer st.cn.errRecover(&err)
  1067. st.exec(v)
  1068. res, _, err = st.cn.readExecuteResponse("simple query")
  1069. return res, err
  1070. }
  1071. func (st *stmt) exec(v []driver.Value) {
  1072. if len(v) >= 65536 {
  1073. errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(v))
  1074. }
  1075. if len(v) != len(st.paramTyps) {
  1076. errorf("got %d parameters but the statement requires %d", len(v), len(st.paramTyps))
  1077. }
  1078. cn := st.cn
  1079. w := cn.writeBuf('B')
  1080. w.byte(0) // unnamed portal
  1081. w.string(st.name)
  1082. if cn.binaryParameters {
  1083. cn.sendBinaryParameters(w, v)
  1084. } else {
  1085. w.int16(0)
  1086. w.int16(len(v))
  1087. for i, x := range v {
  1088. if x == nil {
  1089. w.int32(-1)
  1090. } else {
  1091. b := encode(&cn.parameterStatus, x, st.paramTyps[i])
  1092. w.int32(len(b))
  1093. w.bytes(b)
  1094. }
  1095. }
  1096. }
  1097. w.bytes(st.colFmtData)
  1098. w.next('E')
  1099. w.byte(0)
  1100. w.int32(0)
  1101. w.next('S')
  1102. cn.send(w)
  1103. cn.readBindResponse()
  1104. cn.postExecuteWorkaround()
  1105. }
  1106. func (st *stmt) NumInput() int {
  1107. return len(st.paramTyps)
  1108. }
  1109. // parseComplete parses the "command tag" from a CommandComplete message, and
  1110. // returns the number of rows affected (if applicable) and a string
  1111. // identifying only the command that was executed, e.g. "ALTER TABLE". If the
  1112. // command tag could not be parsed, parseComplete panics.
  1113. func (cn *conn) parseComplete(commandTag string) (driver.Result, string) {
  1114. commandsWithAffectedRows := []string{
  1115. "SELECT ",
  1116. // INSERT is handled below
  1117. "UPDATE ",
  1118. "DELETE ",
  1119. "FETCH ",
  1120. "MOVE ",
  1121. "COPY ",
  1122. }
  1123. var affectedRows *string
  1124. for _, tag := range commandsWithAffectedRows {
  1125. if strings.HasPrefix(commandTag, tag) {
  1126. t := commandTag[len(tag):]
  1127. affectedRows = &t
  1128. commandTag = tag[:len(tag)-1]
  1129. break
  1130. }
  1131. }
  1132. // INSERT also includes the oid of the inserted row in its command tag.
  1133. // Oids in user tables are deprecated, and the oid is only returned when
  1134. // exactly one row is inserted, so it's unlikely to be of value to any
  1135. // real-world application and we can ignore it.
  1136. if affectedRows == nil && strings.HasPrefix(commandTag, "INSERT ") {
  1137. parts := strings.Split(commandTag, " ")
  1138. if len(parts) != 3 {
  1139. cn.bad = true
  1140. errorf("unexpected INSERT command tag %s", commandTag)
  1141. }
  1142. affectedRows = &parts[len(parts)-1]
  1143. commandTag = "INSERT"
  1144. }
  1145. // There should be no affected rows attached to the tag, just return it
  1146. if affectedRows == nil {
  1147. return driver.RowsAffected(0), commandTag
  1148. }
  1149. n, err := strconv.ParseInt(*affectedRows, 10, 64)
  1150. if err != nil {
  1151. cn.bad = true
  1152. errorf("could not parse commandTag: %s", err)
  1153. }
  1154. return driver.RowsAffected(n), commandTag
  1155. }
  1156. type rows struct {
  1157. cn *conn
  1158. colNames []string
  1159. colTyps []oid.Oid
  1160. colFmts []format
  1161. done bool
  1162. rb readBuf
  1163. }
  1164. func (rs *rows) Close() error {
  1165. // no need to look at cn.bad as Next() will
  1166. for {
  1167. err := rs.Next(nil)
  1168. switch err {
  1169. case nil:
  1170. case io.EOF:
  1171. return nil
  1172. default:
  1173. return err
  1174. }
  1175. }
  1176. }
  1177. func (rs *rows) Columns() []string {
  1178. return rs.colNames
  1179. }
  1180. func (rs *rows) Next(dest []driver.Value) (err error) {
  1181. if rs.done {
  1182. return io.EOF
  1183. }
  1184. conn := rs.cn
  1185. if conn.bad {
  1186. return driver.ErrBadConn
  1187. }
  1188. defer conn.errRecover(&err)
  1189. for {
  1190. t := conn.recv1Buf(&rs.rb)
  1191. switch t {
  1192. case 'E':
  1193. err = parseError(&rs.rb)
  1194. case 'C', 'I':
  1195. continue
  1196. case 'Z':
  1197. conn.processReadyForQuery(&rs.rb)
  1198. rs.done = true
  1199. if err != nil {
  1200. return err
  1201. }
  1202. return io.EOF
  1203. case 'D':
  1204. n := rs.rb.int16()
  1205. if err != nil {
  1206. conn.bad = true
  1207. errorf("unexpected DataRow after error %s", err)
  1208. }
  1209. if n < len(dest) {
  1210. dest = dest[:n]
  1211. }
  1212. for i := range dest {
  1213. l := rs.rb.int32()
  1214. if l == -1 {
  1215. dest[i] = nil
  1216. continue
  1217. }
  1218. dest[i] = decode(&conn.parameterStatus, rs.rb.next(l), rs.colTyps[i], rs.colFmts[i])
  1219. }
  1220. return
  1221. default:
  1222. errorf("unexpected message after execute: %q", t)
  1223. }
  1224. }
  1225. }
  1226. // QuoteIdentifier quotes an "identifier" (e.g. a table or a column name) to be
  1227. // used as part of an SQL statement. For example:
  1228. //
  1229. // tblname := "my_table"
  1230. // data := "my_data"
  1231. // err = db.Exec(fmt.Sprintf("INSERT INTO %s VALUES ($1)", pq.QuoteIdentifier(tblname)), data)
  1232. //
  1233. // Any double quotes in name will be escaped. The quoted identifier will be
  1234. // case sensitive when used in a query. If the input string contains a zero
  1235. // byte, the result will be truncated immediately before it.
  1236. func QuoteIdentifier(name string) string {
  1237. end := strings.IndexRune(name, 0)
  1238. if end > -1 {
  1239. name = name[:end]
  1240. }
  1241. return `"` + strings.Replace(name, `"`, `""`, -1) + `"`
  1242. }
  1243. func md5s(s string) string {
  1244. h := md5.New()
  1245. h.Write([]byte(s))
  1246. return fmt.Sprintf("%x", h.Sum(nil))
  1247. }
  1248. func (cn *conn) sendBinaryParameters(b *writeBuf, args []driver.Value) {
  1249. // Do one pass over the parameters to see if we're going to send any of
  1250. // them over in binary. If we are, create a paramFormats array at the
  1251. // same time.
  1252. var paramFormats []int
  1253. for i, x := range args {
  1254. _, ok := x.([]byte)
  1255. if ok {
  1256. if paramFormats == nil {
  1257. paramFormats = make([]int, len(args))
  1258. }
  1259. paramFormats[i] = 1
  1260. }
  1261. }
  1262. if paramFormats == nil {
  1263. b.int16(0)
  1264. } else {
  1265. b.int16(len(paramFormats))
  1266. for _, x := range paramFormats {
  1267. b.int16(x)
  1268. }
  1269. }
  1270. b.int16(len(args))
  1271. for _, x := range args {
  1272. if x == nil {
  1273. b.int32(-1)
  1274. } else {
  1275. datum := binaryEncode(&cn.parameterStatus, x)
  1276. b.int32(len(datum))
  1277. b.bytes(datum)
  1278. }
  1279. }
  1280. }
  1281. func (cn *conn) sendBinaryModeQuery(query string, args []driver.Value) {
  1282. if len(args) >= 65536 {
  1283. errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(args))
  1284. }
  1285. b := cn.writeBuf('P')
  1286. b.byte(0) // unnamed statement
  1287. b.string(query)
  1288. b.int16(0)
  1289. b.next('B')
  1290. b.int16(0) // unnamed portal and statement
  1291. cn.sendBinaryParameters(b, args)
  1292. b.bytes(colFmtDataAllText)
  1293. b.next('D')
  1294. b.byte('P')
  1295. b.byte(0) // unnamed portal
  1296. b.next('E')
  1297. b.byte(0)
  1298. b.int32(0)
  1299. b.next('S')
  1300. cn.send(b)
  1301. }
  1302. func (c *conn) processParameterStatus(r *readBuf) {
  1303. var err error
  1304. param := r.string()
  1305. switch param {
  1306. case "server_version":
  1307. var major1 int
  1308. var major2 int
  1309. var minor int
  1310. _, err = fmt.Sscanf(r.string(), "%d.%d.%d", &major1, &major2, &minor)
  1311. if err == nil {
  1312. c.parameterStatus.serverVersion = major1*10000 + major2*100 + minor
  1313. }
  1314. case "TimeZone":
  1315. c.parameterStatus.currentLocation, err = time.LoadLocation(r.string())
  1316. if err != nil {
  1317. c.parameterStatus.currentLocation = nil
  1318. }
  1319. default:
  1320. // ignore
  1321. }
  1322. }
  1323. func (c *conn) processReadyForQuery(r *readBuf) {
  1324. c.txnStatus = transactionStatus(r.byte())
  1325. }
  1326. func (cn *conn) readReadyForQuery() {
  1327. t, r := cn.recv1()
  1328. switch t {
  1329. case 'Z':
  1330. cn.processReadyForQuery(r)
  1331. return
  1332. default:
  1333. cn.bad = true
  1334. errorf("unexpected message %q; expected ReadyForQuery", t)
  1335. }
  1336. }
  1337. func (cn *conn) readParseResponse() {
  1338. t, r := cn.recv1()
  1339. switch t {
  1340. case '1':
  1341. return
  1342. case 'E':
  1343. err := parseError(r)
  1344. cn.readReadyForQuery()
  1345. panic(err)
  1346. default:
  1347. cn.bad = true
  1348. errorf("unexpected Parse response %q", t)
  1349. }
  1350. }
  1351. func (cn *conn) readStatementDescribeResponse() (paramTyps []oid.Oid, colNames []string, colTyps []oid.Oid) {
  1352. for {
  1353. t, r := cn.recv1()
  1354. switch t {
  1355. case 't':
  1356. nparams := r.int16()
  1357. paramTyps = make([]oid.Oid, nparams)
  1358. for i := range paramTyps {
  1359. paramTyps[i] = r.oid()
  1360. }
  1361. case 'n':
  1362. return paramTyps, nil, nil
  1363. case 'T':
  1364. colNames, colTyps = parseStatementRowDescribe(r)
  1365. return paramTyps, colNames, colTyps
  1366. case 'E':
  1367. err := parseError(r)
  1368. cn.readReadyForQuery()
  1369. panic(err)
  1370. default:
  1371. cn.bad = true
  1372. errorf("unexpected Describe statement response %q", t)
  1373. }
  1374. }
  1375. }
  1376. func (cn *conn) readPortalDescribeResponse() (colNames []string, colFmts []format, colTyps []oid.Oid) {
  1377. t, r := cn.recv1()
  1378. switch t {
  1379. case 'T':
  1380. return parsePortalRowDescribe(r)
  1381. case 'n':
  1382. return nil, nil, nil
  1383. case 'E':
  1384. err := parseError(r)
  1385. cn.readReadyForQuery()
  1386. panic(err)
  1387. default:
  1388. cn.bad = true
  1389. errorf("unexpected Describe response %q", t)
  1390. }
  1391. panic("not reached")
  1392. }
  1393. func (cn *conn) readBindResponse() {
  1394. t, r := cn.recv1()
  1395. switch t {
  1396. case '2':
  1397. return
  1398. case 'E':
  1399. err := parseError(r)
  1400. cn.readReadyForQuery()
  1401. panic(err)
  1402. default:
  1403. cn.bad = true
  1404. errorf("unexpected Bind response %q", t)
  1405. }
  1406. }
  1407. func (cn *conn) postExecuteWorkaround() {
  1408. // Work around a bug in sql.DB.QueryRow: in Go 1.2 and earlier it ignores
  1409. // any errors from rows.Next, which masks errors that happened during the
  1410. // execution of the query. To avoid the problem in common cases, we wait
  1411. // here for one more message from the database. If it's not an error the
  1412. // query will likely succeed (or perhaps has already, if it's a
  1413. // CommandComplete), so we push the message into the conn struct; recv1
  1414. // will return it as the next message for rows.Next or rows.Close.
  1415. // However, if it's an error, we wait until ReadyForQuery and then return
  1416. // the error to our caller.
  1417. for {
  1418. t, r := cn.recv1()
  1419. switch t {
  1420. case 'E':
  1421. err := parseError(r)
  1422. cn.readReadyForQuery()
  1423. panic(err)
  1424. case 'C', 'D', 'I':
  1425. // the query didn't fail, but we can't process this message
  1426. cn.saveMessage(t, r)
  1427. return
  1428. default:
  1429. cn.bad = true
  1430. errorf("unexpected message during extended query execution: %q", t)
  1431. }
  1432. }
  1433. }
  1434. // Only for Exec(), since we ignore the returned data
  1435. func (cn *conn) readExecuteResponse(protocolState string) (res driver.Result, commandTag string, err error) {
  1436. for {
  1437. t, r := cn.recv1()
  1438. switch t {
  1439. case 'C':
  1440. if err != nil {
  1441. cn.bad = true
  1442. errorf("unexpected CommandComplete after error %s", err)
  1443. }
  1444. res, commandTag = cn.parseComplete(r.string())
  1445. case 'Z':
  1446. cn.processReadyForQuery(r)
  1447. return res, commandTag, err
  1448. case 'E':
  1449. err = parseError(r)
  1450. case 'T', 'D', 'I':
  1451. if err != nil {
  1452. cn.bad = true
  1453. errorf("unexpected %q after error %s", t, err)
  1454. }
  1455. // ignore any results
  1456. default:
  1457. cn.bad = true
  1458. errorf("unknown %s response: %q", protocolState, t)
  1459. }
  1460. }
  1461. }
  1462. func parseStatementRowDescribe(r *readBuf) (colNames []string, colTyps []oid.Oid) {
  1463. n := r.int16()
  1464. colNames = make([]string, n)
  1465. colTyps = make([]oid.Oid, n)
  1466. for i := range colNames {
  1467. colNames[i] = r.string()
  1468. r.next(6)
  1469. colTyps[i] = r.oid()
  1470. r.next(6)
  1471. // format code not known when describing a statement; always 0
  1472. r.next(2)
  1473. }
  1474. return
  1475. }
  1476. func parsePortalRowDescribe(r *readBuf) (colNames []string, colFmts []format, colTyps []oid.Oid) {
  1477. n := r.int16()
  1478. colNames = make([]string, n)
  1479. colFmts = make([]format, n)
  1480. colTyps = make([]oid.Oid, n)
  1481. for i := range colNames {
  1482. colNames[i] = r.string()
  1483. r.next(6)
  1484. colTyps[i] = r.oid()
  1485. r.next(6)
  1486. colFmts[i] = format(r.int16())
  1487. }
  1488. return
  1489. }
  1490. // parseEnviron tries to mimic some of libpq's environment handling
  1491. //
  1492. // To ease testing, it does not directly reference os.Environ, but is
  1493. // designed to accept its output.
  1494. //
  1495. // Environment-set connection information is intended to have a higher
  1496. // precedence than a library default but lower than any explicitly
  1497. // passed information (such as in the URL or connection string).
  1498. func parseEnviron(env []string) (out map[string]string) {
  1499. out = make(map[string]string)
  1500. for _, v := range env {
  1501. parts := strings.SplitN(v, "=", 2)
  1502. accrue := func(keyname string) {
  1503. out[keyname] = parts[1]
  1504. }
  1505. unsupported := func() {
  1506. panic(fmt.Sprintf("setting %v not supported", parts[0]))
  1507. }
  1508. // The order of these is the same as is seen in the
  1509. // PostgreSQL 9.1 manual. Unsupported but well-defined
  1510. // keys cause a panic; these should be unset prior to
  1511. // execution. Options which pq expects to be set to a
  1512. // certain value are allowed, but must be set to that
  1513. // value if present (they can, of course, be absent).
  1514. switch parts[0] {
  1515. case "PGHOST":
  1516. accrue("host")
  1517. case "PGHOSTADDR":
  1518. unsupported()
  1519. case "PGPORT":
  1520. accrue("port")
  1521. case "PGDATABASE":
  1522. accrue("dbname")
  1523. case "PGUSER":
  1524. accrue("user")
  1525. case "PGPASSWORD":
  1526. accrue("password")
  1527. case "PGPASSFILE", "PGSERVICE", "PGSERVICEFILE", "PGREALM":
  1528. unsupported()
  1529. case "PGOPTIONS":
  1530. accrue("options")
  1531. case "PGAPPNAME":
  1532. accrue("application_name")
  1533. case "PGSSLMODE":
  1534. accrue("sslmode")
  1535. case "PGSSLCERT":
  1536. accrue("sslcert")
  1537. case "PGSSLKEY":
  1538. accrue("sslkey")
  1539. case "PGSSLROOTCERT":
  1540. accrue("sslrootcert")
  1541. case "PGREQUIRESSL", "PGSSLCRL":
  1542. unsupported()
  1543. case "PGREQUIREPEER":
  1544. unsupported()
  1545. case "PGKRBSRVNAME", "PGGSSLIB":
  1546. unsupported()
  1547. case "PGCONNECT_TIMEOUT":
  1548. accrue("connect_timeout")
  1549. case "PGCLIENTENCODING":
  1550. accrue("client_encoding")
  1551. case "PGDATESTYLE":
  1552. accrue("datestyle")
  1553. case "PGTZ":
  1554. accrue("timezone")
  1555. case "PGGEQO":
  1556. accrue("geqo")
  1557. case "PGSYSCONFDIR", "PGLOCALEDIR":
  1558. unsupported()
  1559. }
  1560. }
  1561. return out
  1562. }
  1563. // isUTF8 returns whether name is a fuzzy variation of the string "UTF-8".
  1564. func isUTF8(name string) bool {
  1565. // Recognize all sorts of silly things as "UTF-8", like Postgres does
  1566. s := strings.Map(alnumLowerASCII, name)
  1567. return s == "utf8" || s == "unicode"
  1568. }
  1569. func alnumLowerASCII(ch rune) rune {
  1570. if 'A' <= ch && ch <= 'Z' {
  1571. return ch + ('a' - 'A')
  1572. }
  1573. if 'a' <= ch && ch <= 'z' || '0' <= ch && ch <= '9' {
  1574. return ch
  1575. }
  1576. return -1 // discard
  1577. }