You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mysql.go 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. // Copyright 2015 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package dialects
  5. import (
  6. "context"
  7. "crypto/tls"
  8. "errors"
  9. "fmt"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "xorm.io/xorm/core"
  15. "xorm.io/xorm/schemas"
  16. )
  17. var (
  18. mysqlReservedWords = map[string]bool{
  19. "ADD": true,
  20. "ALL": true,
  21. "ALTER": true,
  22. "ANALYZE": true,
  23. "AND": true,
  24. "AS": true,
  25. "ASC": true,
  26. "ASENSITIVE": true,
  27. "BEFORE": true,
  28. "BETWEEN": true,
  29. "BIGINT": true,
  30. "BINARY": true,
  31. "BLOB": true,
  32. "BOTH": true,
  33. "BY": true,
  34. "CALL": true,
  35. "CASCADE": true,
  36. "CASE": true,
  37. "CHANGE": true,
  38. "CHAR": true,
  39. "CHARACTER": true,
  40. "CHECK": true,
  41. "COLLATE": true,
  42. "COLUMN": true,
  43. "CONDITION": true,
  44. "CONNECTION": true,
  45. "CONSTRAINT": true,
  46. "CONTINUE": true,
  47. "CONVERT": true,
  48. "CREATE": true,
  49. "CROSS": true,
  50. "CURRENT_DATE": true,
  51. "CURRENT_TIME": true,
  52. "CURRENT_TIMESTAMP": true,
  53. "CURRENT_USER": true,
  54. "CURSOR": true,
  55. "DATABASE": true,
  56. "DATABASES": true,
  57. "DAY_HOUR": true,
  58. "DAY_MICROSECOND": true,
  59. "DAY_MINUTE": true,
  60. "DAY_SECOND": true,
  61. "DEC": true,
  62. "DECIMAL": true,
  63. "DECLARE": true,
  64. "DEFAULT": true,
  65. "DELAYED": true,
  66. "DELETE": true,
  67. "DESC": true,
  68. "DESCRIBE": true,
  69. "DETERMINISTIC": true,
  70. "DISTINCT": true,
  71. "DISTINCTROW": true,
  72. "DIV": true,
  73. "DOUBLE": true,
  74. "DROP": true,
  75. "DUAL": true,
  76. "EACH": true,
  77. "ELSE": true,
  78. "ELSEIF": true,
  79. "ENCLOSED": true,
  80. "ESCAPED": true,
  81. "EXISTS": true,
  82. "EXIT": true,
  83. "EXPLAIN": true,
  84. "FALSE": true,
  85. "FETCH": true,
  86. "FLOAT": true,
  87. "FLOAT4": true,
  88. "FLOAT8": true,
  89. "FOR": true,
  90. "FORCE": true,
  91. "FOREIGN": true,
  92. "FROM": true,
  93. "FULLTEXT": true,
  94. "GOTO": true,
  95. "GRANT": true,
  96. "GROUP": true,
  97. "HAVING": true,
  98. "HIGH_PRIORITY": true,
  99. "HOUR_MICROSECOND": true,
  100. "HOUR_MINUTE": true,
  101. "HOUR_SECOND": true,
  102. "IF": true,
  103. "IGNORE": true,
  104. "IN": true, "INDEX": true,
  105. "INFILE": true, "INNER": true, "INOUT": true,
  106. "INSENSITIVE": true, "INSERT": true, "INT": true,
  107. "INT1": true, "INT2": true, "INT3": true,
  108. "INT4": true, "INT8": true, "INTEGER": true,
  109. "INTERVAL": true, "INTO": true, "IS": true,
  110. "ITERATE": true, "JOIN": true, "KEY": true,
  111. "KEYS": true, "KILL": true, "LABEL": true,
  112. "LEADING": true, "LEAVE": true, "LEFT": true,
  113. "LIKE": true, "LIMIT": true, "LINEAR": true,
  114. "LINES": true, "LOAD": true, "LOCALTIME": true,
  115. "LOCALTIMESTAMP": true, "LOCK": true, "LONG": true,
  116. "LONGBLOB": true, "LONGTEXT": true, "LOOP": true,
  117. "LOW_PRIORITY": true, "MATCH": true, "MEDIUMBLOB": true,
  118. "MEDIUMINT": true, "MEDIUMTEXT": true, "MIDDLEINT": true,
  119. "MINUTE_MICROSECOND": true, "MINUTE_SECOND": true, "MOD": true,
  120. "MODIFIES": true, "NATURAL": true, "NOT": true,
  121. "NO_WRITE_TO_BINLOG": true, "NULL": true, "NUMERIC": true,
  122. "ON OPTIMIZE": true, "OPTION": true,
  123. "OPTIONALLY": true, "OR": true, "ORDER": true,
  124. "OUT": true, "OUTER": true, "OUTFILE": true,
  125. "PRECISION": true, "PRIMARY": true, "PROCEDURE": true,
  126. "PURGE": true, "RAID0": true, "RANGE": true,
  127. "READ": true, "READS": true, "REAL": true,
  128. "REFERENCES": true, "REGEXP": true, "RELEASE": true,
  129. "RENAME": true, "REPEAT": true, "REPLACE": true,
  130. "REQUIRE": true, "RESTRICT": true, "RETURN": true,
  131. "REVOKE": true, "RIGHT": true, "RLIKE": true,
  132. "SCHEMA": true, "SCHEMAS": true, "SECOND_MICROSECOND": true,
  133. "SELECT": true, "SENSITIVE": true, "SEPARATOR": true,
  134. "SET": true, "SHOW": true, "SMALLINT": true,
  135. "SPATIAL": true, "SPECIFIC": true, "SQL": true,
  136. "SQLEXCEPTION": true, "SQLSTATE": true, "SQLWARNING": true,
  137. "SQL_BIG_RESULT": true, "SQL_CALC_FOUND_ROWS": true, "SQL_SMALL_RESULT": true,
  138. "SSL": true, "STARTING": true, "STRAIGHT_JOIN": true,
  139. "TABLE": true, "TERMINATED": true, "THEN": true,
  140. "TINYBLOB": true, "TINYINT": true, "TINYTEXT": true,
  141. "TO": true, "TRAILING": true, "TRIGGER": true,
  142. "TRUE": true, "UNDO": true, "UNION": true,
  143. "UNIQUE": true, "UNLOCK": true, "UNSIGNED": true,
  144. "UPDATE": true, "USAGE": true, "USE": true,
  145. "USING": true, "UTC_DATE": true, "UTC_TIME": true,
  146. "UTC_TIMESTAMP": true, "VALUES": true, "VARBINARY": true,
  147. "VARCHAR": true,
  148. "VARCHARACTER": true,
  149. "VARYING": true,
  150. "WHEN": true,
  151. "WHERE": true,
  152. "WHILE": true,
  153. "WITH": true,
  154. "WRITE": true,
  155. "X509": true,
  156. "XOR": true,
  157. "YEAR_MONTH": true,
  158. "ZEROFILL": true,
  159. }
  160. mysqlQuoter = schemas.Quoter{'`', '`', schemas.AlwaysReserve}
  161. )
  162. type mysql struct {
  163. Base
  164. net string
  165. addr string
  166. params map[string]string
  167. loc *time.Location
  168. timeout time.Duration
  169. tls *tls.Config
  170. allowAllFiles bool
  171. allowOldPasswords bool
  172. clientFoundRows bool
  173. rowFormat string
  174. }
  175. func (db *mysql) Init(uri *URI) error {
  176. db.quoter = mysqlQuoter
  177. return db.Base.Init(db, uri)
  178. }
  179. func (db *mysql) SetParams(params map[string]string) {
  180. rowFormat, ok := params["rowFormat"]
  181. if ok {
  182. var t = strings.ToUpper(rowFormat)
  183. switch t {
  184. case "COMPACT":
  185. fallthrough
  186. case "REDUNDANT":
  187. fallthrough
  188. case "DYNAMIC":
  189. fallthrough
  190. case "COMPRESSED":
  191. db.rowFormat = t
  192. break
  193. default:
  194. break
  195. }
  196. }
  197. }
  198. func (db *mysql) SQLType(c *schemas.Column) string {
  199. var res string
  200. switch t := c.SQLType.Name; t {
  201. case schemas.Bool:
  202. res = schemas.TinyInt
  203. c.Length = 1
  204. case schemas.Serial:
  205. c.IsAutoIncrement = true
  206. c.IsPrimaryKey = true
  207. c.Nullable = false
  208. res = schemas.Int
  209. case schemas.BigSerial:
  210. c.IsAutoIncrement = true
  211. c.IsPrimaryKey = true
  212. c.Nullable = false
  213. res = schemas.BigInt
  214. case schemas.Bytea:
  215. res = schemas.Blob
  216. case schemas.TimeStampz:
  217. res = schemas.Char
  218. c.Length = 64
  219. case schemas.Enum: // mysql enum
  220. res = schemas.Enum
  221. res += "("
  222. opts := ""
  223. for v := range c.EnumOptions {
  224. opts += fmt.Sprintf(",'%v'", v)
  225. }
  226. res += strings.TrimLeft(opts, ",")
  227. res += ")"
  228. case schemas.Set: // mysql set
  229. res = schemas.Set
  230. res += "("
  231. opts := ""
  232. for v := range c.SetOptions {
  233. opts += fmt.Sprintf(",'%v'", v)
  234. }
  235. res += strings.TrimLeft(opts, ",")
  236. res += ")"
  237. case schemas.NVarchar:
  238. res = schemas.Varchar
  239. case schemas.Uuid:
  240. res = schemas.Varchar
  241. c.Length = 40
  242. case schemas.Json:
  243. res = schemas.Text
  244. default:
  245. res = t
  246. }
  247. hasLen1 := (c.Length > 0)
  248. hasLen2 := (c.Length2 > 0)
  249. if res == schemas.BigInt && !hasLen1 && !hasLen2 {
  250. c.Length = 20
  251. hasLen1 = true
  252. }
  253. if hasLen2 {
  254. res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
  255. } else if hasLen1 {
  256. res += "(" + strconv.Itoa(c.Length) + ")"
  257. }
  258. return res
  259. }
  260. func (db *mysql) IsReserved(name string) bool {
  261. _, ok := mysqlReservedWords[strings.ToUpper(name)]
  262. return ok
  263. }
  264. func (db *mysql) AutoIncrStr() string {
  265. return "AUTO_INCREMENT"
  266. }
  267. func (db *mysql) IndexCheckSQL(tableName, idxName string) (string, []interface{}) {
  268. args := []interface{}{db.uri.DBName, tableName, idxName}
  269. sql := "SELECT `INDEX_NAME` FROM `INFORMATION_SCHEMA`.`STATISTICS`"
  270. sql += " WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `INDEX_NAME`=?"
  271. return sql, args
  272. }
  273. func (db *mysql) IsTableExist(queryer core.Queryer, ctx context.Context, tableName string) (bool, error) {
  274. sql := "SELECT `TABLE_NAME` from `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`=? and `TABLE_NAME`=?"
  275. return db.HasRecords(queryer, ctx, sql, db.uri.DBName, tableName)
  276. }
  277. func (db *mysql) AddColumnSQL(tableName string, col *schemas.Column) string {
  278. quoter := db.dialect.Quoter()
  279. sql := fmt.Sprintf("ALTER TABLE %v ADD %v", quoter.Quote(tableName),
  280. db.String(col))
  281. if len(col.Comment) > 0 {
  282. sql += " COMMENT '" + col.Comment + "'"
  283. }
  284. return sql
  285. }
  286. func (db *mysql) GetColumns(queryer core.Queryer, ctx context.Context, tableName string) ([]string, map[string]*schemas.Column, error) {
  287. args := []interface{}{db.uri.DBName, tableName}
  288. s := "SELECT `COLUMN_NAME`, `IS_NULLABLE`, `COLUMN_DEFAULT`, `COLUMN_TYPE`," +
  289. " `COLUMN_KEY`, `EXTRA`,`COLUMN_COMMENT` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?"
  290. rows, err := queryer.QueryContext(ctx, s, args...)
  291. if err != nil {
  292. return nil, nil, err
  293. }
  294. defer rows.Close()
  295. cols := make(map[string]*schemas.Column)
  296. colSeq := make([]string, 0)
  297. for rows.Next() {
  298. col := new(schemas.Column)
  299. col.Indexes = make(map[string]int)
  300. var columnName, isNullable, colType, colKey, extra, comment string
  301. var colDefault *string
  302. err = rows.Scan(&columnName, &isNullable, &colDefault, &colType, &colKey, &extra, &comment)
  303. if err != nil {
  304. return nil, nil, err
  305. }
  306. col.Name = strings.Trim(columnName, "` ")
  307. col.Comment = comment
  308. if "YES" == isNullable {
  309. col.Nullable = true
  310. }
  311. if colDefault != nil {
  312. col.Default = *colDefault
  313. col.DefaultIsEmpty = false
  314. } else {
  315. col.DefaultIsEmpty = true
  316. }
  317. cts := strings.Split(colType, "(")
  318. colName := cts[0]
  319. colType = strings.ToUpper(colName)
  320. var len1, len2 int
  321. if len(cts) == 2 {
  322. idx := strings.Index(cts[1], ")")
  323. if colType == schemas.Enum && cts[1][0] == '\'' { // enum
  324. options := strings.Split(cts[1][0:idx], ",")
  325. col.EnumOptions = make(map[string]int)
  326. for k, v := range options {
  327. v = strings.TrimSpace(v)
  328. v = strings.Trim(v, "'")
  329. col.EnumOptions[v] = k
  330. }
  331. } else if colType == schemas.Set && cts[1][0] == '\'' {
  332. options := strings.Split(cts[1][0:idx], ",")
  333. col.SetOptions = make(map[string]int)
  334. for k, v := range options {
  335. v = strings.TrimSpace(v)
  336. v = strings.Trim(v, "'")
  337. col.SetOptions[v] = k
  338. }
  339. } else {
  340. lens := strings.Split(cts[1][0:idx], ",")
  341. len1, err = strconv.Atoi(strings.TrimSpace(lens[0]))
  342. if err != nil {
  343. return nil, nil, err
  344. }
  345. if len(lens) == 2 {
  346. len2, err = strconv.Atoi(lens[1])
  347. if err != nil {
  348. return nil, nil, err
  349. }
  350. }
  351. }
  352. }
  353. if colType == "FLOAT UNSIGNED" {
  354. colType = "FLOAT"
  355. }
  356. if colType == "DOUBLE UNSIGNED" {
  357. colType = "DOUBLE"
  358. }
  359. col.Length = len1
  360. col.Length2 = len2
  361. if _, ok := schemas.SqlTypes[colType]; ok {
  362. col.SQLType = schemas.SQLType{Name: colType, DefaultLength: len1, DefaultLength2: len2}
  363. } else {
  364. return nil, nil, fmt.Errorf("Unknown colType %v", colType)
  365. }
  366. if colKey == "PRI" {
  367. col.IsPrimaryKey = true
  368. }
  369. if colKey == "UNI" {
  370. // col.is
  371. }
  372. if extra == "auto_increment" {
  373. col.IsAutoIncrement = true
  374. }
  375. if !col.DefaultIsEmpty {
  376. if col.SQLType.IsText() {
  377. col.Default = "'" + col.Default + "'"
  378. } else if col.SQLType.IsTime() && col.Default != "CURRENT_TIMESTAMP" {
  379. col.Default = "'" + col.Default + "'"
  380. }
  381. }
  382. cols[col.Name] = col
  383. colSeq = append(colSeq, col.Name)
  384. }
  385. return colSeq, cols, nil
  386. }
  387. func (db *mysql) GetTables(queryer core.Queryer, ctx context.Context) ([]*schemas.Table, error) {
  388. args := []interface{}{db.uri.DBName}
  389. s := "SELECT `TABLE_NAME`, `ENGINE`, `AUTO_INCREMENT`, `TABLE_COMMENT` from " +
  390. "`INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`=? AND (`ENGINE`='MyISAM' OR `ENGINE` = 'InnoDB' OR `ENGINE` = 'TokuDB')"
  391. rows, err := queryer.QueryContext(ctx, s, args...)
  392. if err != nil {
  393. return nil, err
  394. }
  395. defer rows.Close()
  396. tables := make([]*schemas.Table, 0)
  397. for rows.Next() {
  398. table := schemas.NewEmptyTable()
  399. var name, engine string
  400. var autoIncr, comment *string
  401. err = rows.Scan(&name, &engine, &autoIncr, &comment)
  402. if err != nil {
  403. return nil, err
  404. }
  405. table.Name = name
  406. if comment != nil {
  407. table.Comment = *comment
  408. }
  409. table.StoreEngine = engine
  410. tables = append(tables, table)
  411. }
  412. return tables, nil
  413. }
  414. func (db *mysql) SetQuotePolicy(quotePolicy QuotePolicy) {
  415. switch quotePolicy {
  416. case QuotePolicyNone:
  417. var q = mysqlQuoter
  418. q.IsReserved = schemas.AlwaysNoReserve
  419. db.quoter = q
  420. case QuotePolicyReserved:
  421. var q = mysqlQuoter
  422. q.IsReserved = db.IsReserved
  423. db.quoter = q
  424. case QuotePolicyAlways:
  425. fallthrough
  426. default:
  427. db.quoter = mysqlQuoter
  428. }
  429. }
  430. func (db *mysql) GetIndexes(queryer core.Queryer, ctx context.Context, tableName string) (map[string]*schemas.Index, error) {
  431. args := []interface{}{db.uri.DBName, tableName}
  432. s := "SELECT `INDEX_NAME`, `NON_UNIQUE`, `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`STATISTICS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?"
  433. rows, err := queryer.QueryContext(ctx, s, args...)
  434. if err != nil {
  435. return nil, err
  436. }
  437. defer rows.Close()
  438. indexes := make(map[string]*schemas.Index, 0)
  439. for rows.Next() {
  440. var indexType int
  441. var indexName, colName, nonUnique string
  442. err = rows.Scan(&indexName, &nonUnique, &colName)
  443. if err != nil {
  444. return nil, err
  445. }
  446. if indexName == "PRIMARY" {
  447. continue
  448. }
  449. if "YES" == nonUnique || nonUnique == "1" {
  450. indexType = schemas.IndexType
  451. } else {
  452. indexType = schemas.UniqueType
  453. }
  454. colName = strings.Trim(colName, "` ")
  455. var isRegular bool
  456. if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
  457. indexName = indexName[5+len(tableName):]
  458. isRegular = true
  459. }
  460. var index *schemas.Index
  461. var ok bool
  462. if index, ok = indexes[indexName]; !ok {
  463. index = new(schemas.Index)
  464. index.IsRegular = isRegular
  465. index.Type = indexType
  466. index.Name = indexName
  467. indexes[indexName] = index
  468. }
  469. index.AddColumn(colName)
  470. }
  471. return indexes, nil
  472. }
  473. func (db *mysql) CreateTableSQL(table *schemas.Table, tableName string) ([]string, bool) {
  474. var sql = "CREATE TABLE IF NOT EXISTS "
  475. if tableName == "" {
  476. tableName = table.Name
  477. }
  478. quoter := db.Quoter()
  479. sql += quoter.Quote(tableName)
  480. sql += " ("
  481. if len(table.ColumnsSeq()) > 0 {
  482. pkList := table.PrimaryKeys
  483. for _, colName := range table.ColumnsSeq() {
  484. col := table.GetColumn(colName)
  485. if col.IsPrimaryKey && len(pkList) == 1 {
  486. sql += db.String(col)
  487. } else {
  488. sql += db.StringNoPk(col)
  489. }
  490. sql = strings.TrimSpace(sql)
  491. if len(col.Comment) > 0 {
  492. sql += " COMMENT '" + col.Comment + "'"
  493. }
  494. sql += ", "
  495. }
  496. if len(pkList) > 1 {
  497. sql += "PRIMARY KEY ( "
  498. sql += quoter.Join(pkList, ",")
  499. sql += " ), "
  500. }
  501. sql = sql[:len(sql)-2]
  502. }
  503. sql += ")"
  504. if table.StoreEngine != "" {
  505. sql += " ENGINE=" + table.StoreEngine
  506. }
  507. var charset = table.Charset
  508. if len(charset) == 0 {
  509. charset = db.URI().Charset
  510. }
  511. if len(charset) != 0 {
  512. sql += " DEFAULT CHARSET " + charset
  513. }
  514. if db.rowFormat != "" {
  515. sql += " ROW_FORMAT=" + db.rowFormat
  516. }
  517. return []string{sql}, true
  518. }
  519. func (db *mysql) Filters() []Filter {
  520. return []Filter{}
  521. }
  522. type mymysqlDriver struct {
  523. }
  524. func (p *mymysqlDriver) Parse(driverName, dataSourceName string) (*URI, error) {
  525. uri := &URI{DBType: schemas.MYSQL}
  526. pd := strings.SplitN(dataSourceName, "*", 2)
  527. if len(pd) == 2 {
  528. // Parse protocol part of URI
  529. p := strings.SplitN(pd[0], ":", 2)
  530. if len(p) != 2 {
  531. return nil, errors.New("Wrong protocol part of URI")
  532. }
  533. uri.Proto = p[0]
  534. options := strings.Split(p[1], ",")
  535. uri.Raddr = options[0]
  536. for _, o := range options[1:] {
  537. kv := strings.SplitN(o, "=", 2)
  538. var k, v string
  539. if len(kv) == 2 {
  540. k, v = kv[0], kv[1]
  541. } else {
  542. k, v = o, "true"
  543. }
  544. switch k {
  545. case "laddr":
  546. uri.Laddr = v
  547. case "timeout":
  548. to, err := time.ParseDuration(v)
  549. if err != nil {
  550. return nil, err
  551. }
  552. uri.Timeout = to
  553. default:
  554. return nil, errors.New("Unknown option: " + k)
  555. }
  556. }
  557. // Remove protocol part
  558. pd = pd[1:]
  559. }
  560. // Parse database part of URI
  561. dup := strings.SplitN(pd[0], "/", 3)
  562. if len(dup) != 3 {
  563. return nil, errors.New("Wrong database part of URI")
  564. }
  565. uri.DBName = dup[0]
  566. uri.User = dup[1]
  567. uri.Passwd = dup[2]
  568. return uri, nil
  569. }
  570. type mysqlDriver struct {
  571. }
  572. func (p *mysqlDriver) Parse(driverName, dataSourceName string) (*URI, error) {
  573. dsnPattern := regexp.MustCompile(
  574. `^(?:(?P<user>.*?)(?::(?P<passwd>.*))?@)?` + // [user[:password]@]
  575. `(?:(?P<net>[^\(]*)(?:\((?P<addr>[^\)]*)\))?)?` + // [net[(addr)]]
  576. `\/(?P<dbname>.*?)` + // /dbname
  577. `(?:\?(?P<params>[^\?]*))?$`) // [?param1=value1&paramN=valueN]
  578. matches := dsnPattern.FindStringSubmatch(dataSourceName)
  579. // tlsConfigRegister := make(map[string]*tls.Config)
  580. names := dsnPattern.SubexpNames()
  581. uri := &URI{DBType: schemas.MYSQL}
  582. for i, match := range matches {
  583. switch names[i] {
  584. case "dbname":
  585. uri.DBName = match
  586. case "params":
  587. if len(match) > 0 {
  588. kvs := strings.Split(match, "&")
  589. for _, kv := range kvs {
  590. splits := strings.Split(kv, "=")
  591. if len(splits) == 2 {
  592. switch splits[0] {
  593. case "charset":
  594. uri.Charset = splits[1]
  595. }
  596. }
  597. }
  598. }
  599. }
  600. }
  601. return uri, nil
  602. }