mysql_dialect.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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 xorm
  5. import (
  6. "crypto/tls"
  7. "errors"
  8. "fmt"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/xormplus/core"
  13. )
  14. var (
  15. mysqlReservedWords = map[string]bool{
  16. "ADD": true,
  17. "ALL": true,
  18. "ALTER": true,
  19. "ANALYZE": true,
  20. "AND": true,
  21. "AS": true,
  22. "ASC": true,
  23. "ASENSITIVE": true,
  24. "BEFORE": true,
  25. "BETWEEN": true,
  26. "BIGINT": true,
  27. "BINARY": true,
  28. "BLOB": true,
  29. "BOTH": true,
  30. "BY": true,
  31. "CALL": true,
  32. "CASCADE": true,
  33. "CASE": true,
  34. "CHANGE": true,
  35. "CHAR": true,
  36. "CHARACTER": true,
  37. "CHECK": true,
  38. "COLLATE": true,
  39. "COLUMN": true,
  40. "CONDITION": true,
  41. "CONNECTION": true,
  42. "CONSTRAINT": true,
  43. "CONTINUE": true,
  44. "CONVERT": true,
  45. "CREATE": true,
  46. "CROSS": true,
  47. "CURRENT_DATE": true,
  48. "CURRENT_TIME": true,
  49. "CURRENT_TIMESTAMP": true,
  50. "CURRENT_USER": true,
  51. "CURSOR": true,
  52. "DATABASE": true,
  53. "DATABASES": true,
  54. "DAY_HOUR": true,
  55. "DAY_MICROSECOND": true,
  56. "DAY_MINUTE": true,
  57. "DAY_SECOND": true,
  58. "DEC": true,
  59. "DECIMAL": true,
  60. "DECLARE": true,
  61. "DEFAULT": true,
  62. "DELAYED": true,
  63. "DELETE": true,
  64. "DESC": true,
  65. "DESCRIBE": true,
  66. "DETERMINISTIC": true,
  67. "DISTINCT": true,
  68. "DISTINCTROW": true,
  69. "DIV": true,
  70. "DOUBLE": true,
  71. "DROP": true,
  72. "DUAL": true,
  73. "EACH": true,
  74. "ELSE": true,
  75. "ELSEIF": true,
  76. "ENCLOSED": true,
  77. "ESCAPED": true,
  78. "EXISTS": true,
  79. "EXIT": true,
  80. "EXPLAIN": true,
  81. "FALSE": true,
  82. "FETCH": true,
  83. "FLOAT": true,
  84. "FLOAT4": true,
  85. "FLOAT8": true,
  86. "FOR": true,
  87. "FORCE": true,
  88. "FOREIGN": true,
  89. "FROM": true,
  90. "FULLTEXT": true,
  91. "GOTO": true,
  92. "GRANT": true,
  93. "GROUP": true,
  94. "HAVING": true,
  95. "HIGH_PRIORITY": true,
  96. "HOUR_MICROSECOND": true,
  97. "HOUR_MINUTE": true,
  98. "HOUR_SECOND": true,
  99. "IF": true,
  100. "IGNORE": true,
  101. "IN": true, "INDEX": true,
  102. "INFILE": true, "INNER": true, "INOUT": true,
  103. "INSENSITIVE": true, "INSERT": true, "INT": true,
  104. "INT1": true, "INT2": true, "INT3": true,
  105. "INT4": true, "INT8": true, "INTEGER": true,
  106. "INTERVAL": true, "INTO": true, "IS": true,
  107. "ITERATE": true, "JOIN": true, "KEY": true,
  108. "KEYS": true, "KILL": true, "LABEL": true,
  109. "LEADING": true, "LEAVE": true, "LEFT": true,
  110. "LIKE": true, "LIMIT": true, "LINEAR": true,
  111. "LINES": true, "LOAD": true, "LOCALTIME": true,
  112. "LOCALTIMESTAMP": true, "LOCK": true, "LONG": true,
  113. "LONGBLOB": true, "LONGTEXT": true, "LOOP": true,
  114. "LOW_PRIORITY": true, "MATCH": true, "MEDIUMBLOB": true,
  115. "MEDIUMINT": true, "MEDIUMTEXT": true, "MIDDLEINT": true,
  116. "MINUTE_MICROSECOND": true, "MINUTE_SECOND": true, "MOD": true,
  117. "MODIFIES": true, "NATURAL": true, "NOT": true,
  118. "NO_WRITE_TO_BINLOG": true, "NULL": true, "NUMERIC": true,
  119. "ON OPTIMIZE": true, "OPTION": true,
  120. "OPTIONALLY": true, "OR": true, "ORDER": true,
  121. "OUT": true, "OUTER": true, "OUTFILE": true,
  122. "PRECISION": true, "PRIMARY": true, "PROCEDURE": true,
  123. "PURGE": true, "RAID0": true, "RANGE": true,
  124. "READ": true, "READS": true, "REAL": true,
  125. "REFERENCES": true, "REGEXP": true, "RELEASE": true,
  126. "RENAME": true, "REPEAT": true, "REPLACE": true,
  127. "REQUIRE": true, "RESTRICT": true, "RETURN": true,
  128. "REVOKE": true, "RIGHT": true, "RLIKE": true,
  129. "SCHEMA": true, "SCHEMAS": true, "SECOND_MICROSECOND": true,
  130. "SELECT": true, "SENSITIVE": true, "SEPARATOR": true,
  131. "SET": true, "SHOW": true, "SMALLINT": true,
  132. "SPATIAL": true, "SPECIFIC": true, "SQL": true,
  133. "SQLEXCEPTION": true, "SQLSTATE": true, "SQLWARNING": true,
  134. "SQL_BIG_RESULT": true, "SQL_CALC_FOUND_ROWS": true, "SQL_SMALL_RESULT": true,
  135. "SSL": true, "STARTING": true, "STRAIGHT_JOIN": true,
  136. "TABLE": true, "TERMINATED": true, "THEN": true,
  137. "TINYBLOB": true, "TINYINT": true, "TINYTEXT": true,
  138. "TO": true, "TRAILING": true, "TRIGGER": true,
  139. "TRUE": true, "UNDO": true, "UNION": true,
  140. "UNIQUE": true, "UNLOCK": true, "UNSIGNED": true,
  141. "UPDATE": true, "USAGE": true, "USE": true,
  142. "USING": true, "UTC_DATE": true, "UTC_TIME": true,
  143. "UTC_TIMESTAMP": true, "VALUES": true, "VARBINARY": true,
  144. "VARCHAR": true,
  145. "VARCHARACTER": true,
  146. "VARYING": true,
  147. "WHEN": true,
  148. "WHERE": true,
  149. "WHILE": true,
  150. "WITH": true,
  151. "WRITE": true,
  152. "X509": true,
  153. "XOR": true,
  154. "YEAR_MONTH": true,
  155. "ZEROFILL": true,
  156. }
  157. )
  158. type mysql struct {
  159. core.Base
  160. net string
  161. addr string
  162. params map[string]string
  163. loc *time.Location
  164. timeout time.Duration
  165. tls *tls.Config
  166. allowAllFiles bool
  167. allowOldPasswords bool
  168. clientFoundRows bool
  169. }
  170. func (db *mysql) Init(d *core.DB, uri *core.Uri, drivername, dataSourceName string) error {
  171. return db.Base.Init(d, db, uri, drivername, dataSourceName)
  172. }
  173. func (db *mysql) SqlType(c *core.Column) string {
  174. var res string
  175. switch t := c.SQLType.Name; t {
  176. case core.Bool:
  177. res = core.TinyInt
  178. c.Length = 1
  179. case core.Serial:
  180. c.IsAutoIncrement = true
  181. c.IsPrimaryKey = true
  182. c.Nullable = false
  183. res = core.Int
  184. case core.BigSerial:
  185. c.IsAutoIncrement = true
  186. c.IsPrimaryKey = true
  187. c.Nullable = false
  188. res = core.BigInt
  189. case core.Bytea:
  190. res = core.Blob
  191. case core.TimeStampz:
  192. res = core.Char
  193. c.Length = 64
  194. case core.Enum: //mysql enum
  195. res = core.Enum
  196. res += "("
  197. opts := ""
  198. for v, _ := range c.EnumOptions {
  199. opts += fmt.Sprintf(",'%v'", v)
  200. }
  201. res += strings.TrimLeft(opts, ",")
  202. res += ")"
  203. case core.Set: //mysql set
  204. res = core.Set
  205. res += "("
  206. opts := ""
  207. for v, _ := range c.SetOptions {
  208. opts += fmt.Sprintf(",'%v'", v)
  209. }
  210. res += strings.TrimLeft(opts, ",")
  211. res += ")"
  212. case core.NVarchar:
  213. res = core.Varchar
  214. case core.Uuid:
  215. res = core.Varchar
  216. c.Length = 40
  217. case core.Json:
  218. res = core.Text
  219. default:
  220. res = t
  221. }
  222. var hasLen1 bool = (c.Length > 0)
  223. var hasLen2 bool = (c.Length2 > 0)
  224. if res == core.BigInt && !hasLen1 && !hasLen2 {
  225. c.Length = 20
  226. hasLen1 = true
  227. }
  228. if hasLen2 {
  229. res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
  230. } else if hasLen1 {
  231. res += "(" + strconv.Itoa(c.Length) + ")"
  232. }
  233. return res
  234. }
  235. func (db *mysql) SupportInsertMany() bool {
  236. return true
  237. }
  238. func (db *mysql) IsReserved(name string) bool {
  239. _, ok := mysqlReservedWords[name]
  240. return ok
  241. }
  242. func (db *mysql) Quote(name string) string {
  243. return "`" + name + "`"
  244. }
  245. func (db *mysql) QuoteStr() string {
  246. return "`"
  247. }
  248. func (db *mysql) SupportEngine() bool {
  249. return true
  250. }
  251. func (db *mysql) AutoIncrStr() string {
  252. return "AUTO_INCREMENT"
  253. }
  254. func (db *mysql) SupportCharset() bool {
  255. return true
  256. }
  257. func (db *mysql) IndexOnTable() bool {
  258. return true
  259. }
  260. func (db *mysql) IndexCheckSql(tableName, idxName string) (string, []interface{}) {
  261. args := []interface{}{db.DbName, tableName, idxName}
  262. sql := "SELECT `INDEX_NAME` FROM `INFORMATION_SCHEMA`.`STATISTICS`"
  263. sql += " WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `INDEX_NAME`=?"
  264. return sql, args
  265. }
  266. /*func (db *mysql) ColumnCheckSql(tableName, colName string) (string, []interface{}) {
  267. args := []interface{}{db.DbName, tableName, colName}
  268. sql := "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ?"
  269. return sql, args
  270. }*/
  271. func (db *mysql) TableCheckSql(tableName string) (string, []interface{}) {
  272. args := []interface{}{db.DbName, tableName}
  273. sql := "SELECT `TABLE_NAME` from `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`=? and `TABLE_NAME`=?"
  274. return sql, args
  275. }
  276. func (db *mysql) GetColumns(tableName string) ([]string, map[string]*core.Column, error) {
  277. args := []interface{}{db.DbName, tableName}
  278. s := "SELECT `COLUMN_NAME`, `IS_NULLABLE`, `COLUMN_DEFAULT`, `COLUMN_TYPE`," +
  279. " `COLUMN_KEY`, `EXTRA` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?"
  280. db.LogSQL(s, args)
  281. rows, err := db.DB().Query(s, args...)
  282. if err != nil {
  283. return nil, nil, err
  284. }
  285. defer rows.Close()
  286. cols := make(map[string]*core.Column)
  287. colSeq := make([]string, 0)
  288. for rows.Next() {
  289. col := new(core.Column)
  290. col.Indexes = make(map[string]int)
  291. var columnName, isNullable, colType, colKey, extra string
  292. var colDefault *string
  293. err = rows.Scan(&columnName, &isNullable, &colDefault, &colType, &colKey, &extra)
  294. if err != nil {
  295. return nil, nil, err
  296. }
  297. col.Name = strings.Trim(columnName, "` ")
  298. if "YES" == isNullable {
  299. col.Nullable = true
  300. }
  301. if colDefault != nil {
  302. col.Default = *colDefault
  303. if col.Default == "" {
  304. col.DefaultIsEmpty = true
  305. }
  306. }
  307. cts := strings.Split(colType, "(")
  308. colName := cts[0]
  309. colType = strings.ToUpper(colName)
  310. var len1, len2 int
  311. if len(cts) == 2 {
  312. idx := strings.Index(cts[1], ")")
  313. if colType == core.Enum && cts[1][0] == '\'' { //enum
  314. options := strings.Split(cts[1][0:idx], ",")
  315. col.EnumOptions = make(map[string]int)
  316. for k, v := range options {
  317. v = strings.TrimSpace(v)
  318. v = strings.Trim(v, "'")
  319. col.EnumOptions[v] = k
  320. }
  321. } else if colType == core.Set && cts[1][0] == '\'' {
  322. options := strings.Split(cts[1][0:idx], ",")
  323. col.SetOptions = make(map[string]int)
  324. for k, v := range options {
  325. v = strings.TrimSpace(v)
  326. v = strings.Trim(v, "'")
  327. col.SetOptions[v] = k
  328. }
  329. } else {
  330. lens := strings.Split(cts[1][0:idx], ",")
  331. len1, err = strconv.Atoi(strings.TrimSpace(lens[0]))
  332. if err != nil {
  333. return nil, nil, err
  334. }
  335. if len(lens) == 2 {
  336. len2, err = strconv.Atoi(lens[1])
  337. if err != nil {
  338. return nil, nil, err
  339. }
  340. }
  341. }
  342. }
  343. if colType == "FLOAT UNSIGNED" {
  344. colType = "FLOAT"
  345. }
  346. col.Length = len1
  347. col.Length2 = len2
  348. if _, ok := core.SqlTypes[colType]; ok {
  349. col.SQLType = core.SQLType{Name: colType, DefaultLength: len1, DefaultLength2: len2}
  350. } else {
  351. return nil, nil, errors.New(fmt.Sprintf("unkonw colType %v", colType))
  352. }
  353. if colKey == "PRI" {
  354. col.IsPrimaryKey = true
  355. }
  356. if colKey == "UNI" {
  357. //col.is
  358. }
  359. if extra == "auto_increment" {
  360. col.IsAutoIncrement = true
  361. }
  362. if col.SQLType.IsText() || col.SQLType.IsTime() {
  363. if col.Default != "" {
  364. col.Default = "'" + col.Default + "'"
  365. } else {
  366. if col.DefaultIsEmpty {
  367. col.Default = "''"
  368. }
  369. }
  370. }
  371. cols[col.Name] = col
  372. colSeq = append(colSeq, col.Name)
  373. }
  374. return colSeq, cols, nil
  375. }
  376. func (db *mysql) GetTables() ([]*core.Table, error) {
  377. args := []interface{}{db.DbName}
  378. s := "SELECT `TABLE_NAME`, `ENGINE`, `TABLE_ROWS`, `AUTO_INCREMENT` from " +
  379. "`INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`=? AND (`ENGINE`='MyISAM' OR `ENGINE` = 'InnoDB' OR `ENGINE` = 'TokuDB')"
  380. db.LogSQL(s, args)
  381. rows, err := db.DB().Query(s, args...)
  382. if err != nil {
  383. return nil, err
  384. }
  385. defer rows.Close()
  386. tables := make([]*core.Table, 0)
  387. for rows.Next() {
  388. table := core.NewEmptyTable()
  389. var name, engine, tableRows string
  390. var autoIncr *string
  391. err = rows.Scan(&name, &engine, &tableRows, &autoIncr)
  392. if err != nil {
  393. return nil, err
  394. }
  395. table.Name = name
  396. table.StoreEngine = engine
  397. tables = append(tables, table)
  398. }
  399. return tables, nil
  400. }
  401. func (db *mysql) GetIndexes(tableName string) (map[string]*core.Index, error) {
  402. args := []interface{}{db.DbName, tableName}
  403. s := "SELECT `INDEX_NAME`, `NON_UNIQUE`, `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`STATISTICS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?"
  404. db.LogSQL(s, args)
  405. rows, err := db.DB().Query(s, args...)
  406. if err != nil {
  407. return nil, err
  408. }
  409. defer rows.Close()
  410. indexes := make(map[string]*core.Index, 0)
  411. for rows.Next() {
  412. var indexType int
  413. var indexName, colName, nonUnique string
  414. err = rows.Scan(&indexName, &nonUnique, &colName)
  415. if err != nil {
  416. return nil, err
  417. }
  418. if indexName == "PRIMARY" {
  419. continue
  420. }
  421. if "YES" == nonUnique || nonUnique == "1" {
  422. indexType = core.IndexType
  423. } else {
  424. indexType = core.UniqueType
  425. }
  426. colName = strings.Trim(colName, "` ")
  427. var isRegular bool
  428. if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
  429. indexName = indexName[5+len(tableName) : len(indexName)]
  430. isRegular = true
  431. }
  432. var index *core.Index
  433. var ok bool
  434. if index, ok = indexes[indexName]; !ok {
  435. index = new(core.Index)
  436. index.IsRegular = isRegular
  437. index.Type = indexType
  438. index.Name = indexName
  439. indexes[indexName] = index
  440. }
  441. index.AddColumn(colName)
  442. }
  443. return indexes, nil
  444. }
  445. func (db *mysql) Filters() []core.Filter {
  446. return []core.Filter{&core.IdFilter{}}
  447. }