sqlite3_dialect.go 11 KB

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