mysql_dialect.go 13 KB

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