sqlite3_dialect.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. "database/sql"
  7. "errors"
  8. "fmt"
  9. "regexp"
  10. "strings"
  11. "github.com/go-xorm/core"
  12. )
  13. // func init() {
  14. // RegisterDialect("sqlite3", &sqlite3{})
  15. // }
  16. var (
  17. sqlite3ReservedWords = map[string]bool{
  18. "ABORT": true,
  19. "ACTION": true,
  20. "ADD": true,
  21. "AFTER": true,
  22. "ALL": true,
  23. "ALTER": true,
  24. "ANALYZE": true,
  25. "AND": true,
  26. "AS": true,
  27. "ASC": true,
  28. "ATTACH": true,
  29. "AUTOINCREMENT": true,
  30. "BEFORE": true,
  31. "BEGIN": true,
  32. "BETWEEN": true,
  33. "BY": true,
  34. "CASCADE": true,
  35. "CASE": true,
  36. "CAST": true,
  37. "CHECK": true,
  38. "COLLATE": true,
  39. "COLUMN": true,
  40. "COMMIT": true,
  41. "CONFLICT": true,
  42. "CONSTRAINT": true,
  43. "CREATE": true,
  44. "CROSS": true,
  45. "CURRENT_DATE": true,
  46. "CURRENT_TIME": true,
  47. "CURRENT_TIMESTAMP": true,
  48. "DATABASE": true,
  49. "DEFAULT": true,
  50. "DEFERRABLE": true,
  51. "DEFERRED": true,
  52. "DELETE": true,
  53. "DESC": true,
  54. "DETACH": true,
  55. "DISTINCT": true,
  56. "DROP": true,
  57. "EACH": true,
  58. "ELSE": true,
  59. "END": true,
  60. "ESCAPE": true,
  61. "EXCEPT": true,
  62. "EXCLUSIVE": true,
  63. "EXISTS": true,
  64. "EXPLAIN": true,
  65. "FAIL": true,
  66. "FOR": true,
  67. "FOREIGN": true,
  68. "FROM": true,
  69. "FULL": true,
  70. "GLOB": true,
  71. "GROUP": true,
  72. "HAVING": true,
  73. "IF": true,
  74. "IGNORE": true,
  75. "IMMEDIATE": true,
  76. "IN": true,
  77. "INDEX": true,
  78. "INDEXED": true,
  79. "INITIALLY": true,
  80. "INNER": true,
  81. "INSERT": true,
  82. "INSTEAD": true,
  83. "INTERSECT": true,
  84. "INTO": true,
  85. "IS": true,
  86. "ISNULL": true,
  87. "JOIN": true,
  88. "KEY": true,
  89. "LEFT": true,
  90. "LIKE": true,
  91. "LIMIT": true,
  92. "MATCH": true,
  93. "NATURAL": true,
  94. "NO": true,
  95. "NOT": true,
  96. "NOTNULL": true,
  97. "NULL": true,
  98. "OF": true,
  99. "OFFSET": true,
  100. "ON": true,
  101. "OR": true,
  102. "ORDER": true,
  103. "OUTER": true,
  104. "PLAN": true,
  105. "PRAGMA": true,
  106. "PRIMARY": true,
  107. "QUERY": true,
  108. "RAISE": true,
  109. "RECURSIVE": true,
  110. "REFERENCES": true,
  111. "REGEXP": true,
  112. "REINDEX": true,
  113. "RELEASE": true,
  114. "RENAME": true,
  115. "REPLACE": true,
  116. "RESTRICT": true,
  117. "RIGHT": true,
  118. "ROLLBACK": true,
  119. "ROW": true,
  120. "SAVEPOINT": true,
  121. "SELECT": true,
  122. "SET": true,
  123. "TABLE": true,
  124. "TEMP": true,
  125. "TEMPORARY": true,
  126. "THEN": true,
  127. "TO": true,
  128. "TRANSACTI": true,
  129. "TRIGGER": true,
  130. "UNION": true,
  131. "UNIQUE": true,
  132. "UPDATE": true,
  133. "USING": true,
  134. "VACUUM": true,
  135. "VALUES": true,
  136. "VIEW": true,
  137. "VIRTUAL": true,
  138. "WHEN": true,
  139. "WHERE": true,
  140. "WITH": true,
  141. "WITHOUT": true,
  142. }
  143. )
  144. type sqlite3 struct {
  145. core.Base
  146. }
  147. func (db *sqlite3) Init(d *core.DB, uri *core.Uri, drivername, dataSourceName string) error {
  148. return db.Base.Init(d, db, uri, drivername, dataSourceName)
  149. }
  150. func (db *sqlite3) SqlType(c *core.Column) string {
  151. switch t := c.SQLType.Name; t {
  152. case core.Bool:
  153. if c.Default == "true" {
  154. c.Default = "1"
  155. } else if c.Default == "false" {
  156. c.Default = "0"
  157. }
  158. return core.Integer
  159. case core.Date, core.DateTime, core.TimeStamp, core.Time:
  160. return core.DateTime
  161. case core.TimeStampz:
  162. return core.Text
  163. case core.Char, core.Varchar, core.NVarchar, core.TinyText,
  164. core.Text, core.MediumText, core.LongText, core.Json:
  165. return core.Text
  166. case core.Bit, core.TinyInt, core.SmallInt, core.MediumInt, core.Int, core.Integer, core.BigInt:
  167. return core.Integer
  168. case core.Float, core.Double, core.Real:
  169. return core.Real
  170. case core.Decimal, core.Numeric:
  171. return core.Numeric
  172. case core.TinyBlob, core.Blob, core.MediumBlob, core.LongBlob, core.Bytea, core.Binary, core.VarBinary:
  173. return core.Blob
  174. case core.Serial, core.BigSerial:
  175. c.IsPrimaryKey = true
  176. c.IsAutoIncrement = true
  177. c.Nullable = false
  178. return core.Integer
  179. default:
  180. return t
  181. }
  182. }
  183. func (db *sqlite3) FormatBytes(bs []byte) string {
  184. return fmt.Sprintf("X'%x'", bs)
  185. }
  186. func (db *sqlite3) SupportInsertMany() bool {
  187. return true
  188. }
  189. func (db *sqlite3) IsReserved(name string) bool {
  190. _, ok := sqlite3ReservedWords[name]
  191. return ok
  192. }
  193. func (db *sqlite3) Quote(name string) string {
  194. return "`" + name + "`"
  195. }
  196. func (db *sqlite3) QuoteStr() string {
  197. return "`"
  198. }
  199. func (db *sqlite3) AutoIncrStr() string {
  200. return "AUTOINCREMENT"
  201. }
  202. func (db *sqlite3) SupportEngine() bool {
  203. return false
  204. }
  205. func (db *sqlite3) SupportCharset() bool {
  206. return false
  207. }
  208. func (db *sqlite3) IndexOnTable() bool {
  209. return false
  210. }
  211. func (db *sqlite3) IndexCheckSql(tableName, idxName string) (string, []interface{}) {
  212. args := []interface{}{idxName}
  213. return "SELECT name FROM sqlite_master WHERE type='index' and name = ?", args
  214. }
  215. func (db *sqlite3) TableCheckSql(tableName string) (string, []interface{}) {
  216. args := []interface{}{tableName}
  217. return "SELECT name FROM sqlite_master WHERE type='table' and name = ?", args
  218. }
  219. func (db *sqlite3) DropIndexSql(tableName string, index *core.Index) string {
  220. quote := db.Quote
  221. //var unique string
  222. var idxName string = index.Name
  223. if !strings.HasPrefix(idxName, "UQE_") &&
  224. !strings.HasPrefix(idxName, "IDX_") {
  225. if index.Type == core.UniqueType {
  226. idxName = fmt.Sprintf("UQE_%v_%v", tableName, index.Name)
  227. } else {
  228. idxName = fmt.Sprintf("IDX_%v_%v", tableName, index.Name)
  229. }
  230. }
  231. return fmt.Sprintf("DROP INDEX %v", quote(idxName))
  232. }
  233. func (db *sqlite3) ForUpdateSql(query string) string {
  234. return query
  235. }
  236. /*func (db *sqlite3) ColumnCheckSql(tableName, colName string) (string, []interface{}) {
  237. args := []interface{}{tableName}
  238. sql := "SELECT name FROM sqlite_master WHERE type='table' and name = ? and ((sql like '%`" + colName + "`%') or (sql like '%[" + colName + "]%'))"
  239. return sql, args
  240. }*/
  241. func (db *sqlite3) IsColumnExist(tableName, colName string) (bool, error) {
  242. args := []interface{}{tableName}
  243. query := "SELECT name FROM sqlite_master WHERE type='table' and name = ? and ((sql like '%`" + colName + "`%') or (sql like '%[" + colName + "]%'))"
  244. rows, err := db.DB().Query(query, args...)
  245. if db.Logger != nil {
  246. db.Logger.Info("[sql]", query, args)
  247. }
  248. if err != nil {
  249. return false, err
  250. }
  251. defer rows.Close()
  252. if rows.Next() {
  253. return true, nil
  254. }
  255. return false, nil
  256. }
  257. func (db *sqlite3) GetColumns(tableName string) ([]string, map[string]*core.Column, error) {
  258. args := []interface{}{tableName}
  259. s := "SELECT sql FROM sqlite_master WHERE type='table' and name = ?"
  260. rows, err := db.DB().Query(s, args...)
  261. if db.Logger != nil {
  262. db.Logger.Info("[sql]", s, args)
  263. }
  264. if err != nil {
  265. return nil, nil, err
  266. }
  267. defer rows.Close()
  268. var name string
  269. for rows.Next() {
  270. err = rows.Scan(&name)
  271. if err != nil {
  272. return nil, nil, err
  273. }
  274. break
  275. }
  276. if name == "" {
  277. return nil, nil, errors.New("no table named " + tableName)
  278. }
  279. nStart := strings.Index(name, "(")
  280. nEnd := strings.LastIndex(name, ")")
  281. reg := regexp.MustCompile(`[^\(,\)]*(\([^\(]*\))?`)
  282. colCreates := reg.FindAllString(name[nStart+1:nEnd], -1)
  283. cols := make(map[string]*core.Column)
  284. colSeq := make([]string, 0)
  285. for _, colStr := range colCreates {
  286. reg = regexp.MustCompile(`,\s`)
  287. colStr = reg.ReplaceAllString(colStr, ",")
  288. fields := strings.Fields(strings.TrimSpace(colStr))
  289. col := new(core.Column)
  290. col.Indexes = make(map[string]bool)
  291. col.Nullable = true
  292. col.DefaultIsEmpty = true
  293. for idx, field := range fields {
  294. if idx == 0 {
  295. col.Name = strings.Trim(field, "`[] ")
  296. continue
  297. } else if idx == 1 {
  298. col.SQLType = core.SQLType{field, 0, 0}
  299. }
  300. switch field {
  301. case "PRIMARY":
  302. col.IsPrimaryKey = true
  303. case "AUTOINCREMENT":
  304. col.IsAutoIncrement = true
  305. case "NULL":
  306. if fields[idx-1] == "NOT" {
  307. col.Nullable = false
  308. } else {
  309. col.Nullable = true
  310. }
  311. case "DEFAULT":
  312. col.Default = fields[idx+1]
  313. col.DefaultIsEmpty = false
  314. }
  315. }
  316. if !col.SQLType.IsNumeric() && !col.DefaultIsEmpty {
  317. col.Default = "'" + col.Default + "'"
  318. }
  319. cols[col.Name] = col
  320. colSeq = append(colSeq, col.Name)
  321. }
  322. return colSeq, cols, nil
  323. }
  324. func (db *sqlite3) GetTables() ([]*core.Table, error) {
  325. args := []interface{}{}
  326. s := "SELECT name FROM sqlite_master WHERE type='table'"
  327. rows, err := db.DB().Query(s, args...)
  328. if db.Logger != nil {
  329. db.Logger.Info("[sql]", s, args)
  330. }
  331. if err != nil {
  332. return nil, err
  333. }
  334. defer rows.Close()
  335. tables := make([]*core.Table, 0)
  336. for rows.Next() {
  337. table := core.NewEmptyTable()
  338. err = rows.Scan(&table.Name)
  339. if err != nil {
  340. return nil, err
  341. }
  342. if table.Name == "sqlite_sequence" {
  343. continue
  344. }
  345. tables = append(tables, table)
  346. }
  347. return tables, nil
  348. }
  349. func (db *sqlite3) GetIndexes(tableName string) (map[string]*core.Index, error) {
  350. args := []interface{}{tableName}
  351. s := "SELECT sql FROM sqlite_master WHERE type='index' and tbl_name = ?"
  352. rows, err := db.DB().Query(s, args...)
  353. if db.Logger != nil {
  354. db.Logger.Info("[sql]", s, args)
  355. }
  356. if err != nil {
  357. return nil, err
  358. }
  359. defer rows.Close()
  360. indexes := make(map[string]*core.Index, 0)
  361. for rows.Next() {
  362. var tmpSql sql.NullString
  363. err = rows.Scan(&tmpSql)
  364. if err != nil {
  365. return nil, err
  366. }
  367. if !tmpSql.Valid {
  368. continue
  369. }
  370. sql := tmpSql.String
  371. index := new(core.Index)
  372. nNStart := strings.Index(sql, "INDEX")
  373. nNEnd := strings.Index(sql, "ON")
  374. if nNStart == -1 || nNEnd == -1 {
  375. continue
  376. }
  377. indexName := strings.Trim(sql[nNStart+6:nNEnd], "` []")
  378. if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
  379. index.Name = indexName[5+len(tableName) : len(indexName)]
  380. } else {
  381. index.Name = indexName
  382. }
  383. if strings.HasPrefix(sql, "CREATE UNIQUE INDEX") {
  384. index.Type = core.UniqueType
  385. } else {
  386. index.Type = core.IndexType
  387. }
  388. nStart := strings.Index(sql, "(")
  389. nEnd := strings.Index(sql, ")")
  390. colIndexes := strings.Split(sql[nStart+1:nEnd], ",")
  391. index.Cols = make([]string, 0)
  392. for _, col := range colIndexes {
  393. index.Cols = append(index.Cols, strings.Trim(col, "` []"))
  394. }
  395. indexes[index.Name] = index
  396. }
  397. return indexes, nil
  398. }
  399. func (db *sqlite3) Filters() []core.Filter {
  400. return []core.Filter{&core.IdFilter{}}
  401. }