conn.go 35 KB

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