driver.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2012 Julien Schmidt. All rights reserved.
  2. // http://www.julienschmidt.com
  3. //
  4. // This Source Code Form is subject to the terms of the Mozilla Public
  5. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  6. // You can obtain one at http://mozilla.org/MPL/2.0/.
  7. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
  8. package mysql
  9. import (
  10. "database/sql"
  11. "database/sql/driver"
  12. "net"
  13. "time"
  14. )
  15. type mysqlDriver struct{}
  16. // Open new Connection.
  17. // See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how
  18. // the DSN string is formated
  19. func (d *mysqlDriver) Open(dsn string) (driver.Conn, error) {
  20. var err error
  21. // New mysqlConn
  22. mc := &mysqlConn{
  23. maxPacketAllowed: maxPacketSize,
  24. maxWriteSize: maxPacketSize - 1,
  25. }
  26. mc.cfg, err = parseDSN(dsn)
  27. if err != nil {
  28. return nil, err
  29. }
  30. // Connect to Server
  31. if _, ok := mc.cfg.params["timeout"]; ok { // with timeout
  32. var timeout time.Duration
  33. timeout, err = time.ParseDuration(mc.cfg.params["timeout"])
  34. if err == nil {
  35. mc.netConn, err = net.DialTimeout(mc.cfg.net, mc.cfg.addr, timeout)
  36. }
  37. } else { // no timeout
  38. mc.netConn, err = net.Dial(mc.cfg.net, mc.cfg.addr)
  39. }
  40. if err != nil {
  41. return nil, err
  42. }
  43. mc.buf = newBuffer(mc.netConn)
  44. // Reading Handshake Initialization Packet
  45. err = mc.readInitPacket()
  46. if err != nil {
  47. return nil, err
  48. }
  49. // Send Client Authentication Packet
  50. err = mc.writeAuthPacket()
  51. if err != nil {
  52. return nil, err
  53. }
  54. // Read Result Packet
  55. err = mc.readResultOK()
  56. if err != nil {
  57. return nil, err
  58. }
  59. // Get max allowed packet size
  60. maxap, err := mc.getSystemVar("max_allowed_packet")
  61. if err != nil {
  62. return nil, err
  63. }
  64. mc.maxPacketAllowed = stringToInt(maxap) - 1
  65. if mc.maxPacketAllowed < maxPacketSize {
  66. mc.maxWriteSize = mc.maxPacketAllowed
  67. }
  68. // Handle DSN Params
  69. err = mc.handleParams()
  70. if err != nil {
  71. return nil, err
  72. }
  73. return mc, err
  74. }
  75. func init() {
  76. sql.Register("mysql", &mysqlDriver{})
  77. }