sqlite3_dialect.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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.Date, core.DateTime, core.TimeStamp, core.Time:
  152. return core.DateTime
  153. case core.TimeStampz:
  154. return core.Text
  155. case core.Char, core.Varchar, core.NVarchar, core.TinyText,
  156. core.Text, core.MediumText, core.LongText, core.Json:
  157. return core.Text
  158. case core.Bit, core.TinyInt, core.SmallInt, core.MediumInt, core.Int, core.Integer, core.BigInt, core.Bool:
  159. return core.Integer
  160. case core.Float, core.Double, core.Real:
  161. return core.Real
  162. case core.Decimal, core.Numeric:
  163. return core.Numeric
  164. case core.TinyBlob, core.Blob, core.MediumBlob, core.LongBlob, core.Bytea, core.Binary, core.VarBinary:
  165. return core.Blob
  166. case core.Serial, core.BigSerial:
  167. c.IsPrimaryKey = true
  168. c.IsAutoIncrement = true
  169. c.Nullable = false
  170. return core.Integer
  171. default:
  172. return t
  173. }
  174. }
  175. func (db *sqlite3) FormatBytes(bs []byte) string {
  176. return fmt.Sprintf("X'%x'", bs)
  177. }
  178. func (db *sqlite3) SupportInsertMany() bool {
  179. return true
  180. }
  181. func (db *sqlite3) IsReserved(name string) bool {
  182. _, ok := sqlite3ReservedWords[name]
  183. return ok
  184. }
  185. func (db *sqlite3) Quote(name string) string {
  186. return "`" + name + "`"
  187. }
  188. func (db *sqlite3) QuoteStr() string {
  189. return "`"
  190. }
  191. func (db *sqlite3) AutoIncrStr() string {
  192. return "AUTOINCREMENT"
  193. }
  194. func (db *sqlite3) SupportEngine() bool {
  195. return false
  196. }
  197. func (db *sqlite3) SupportCharset() bool {
  198. return false
  199. }
  200. func (db *sqlite3) IndexOnTable() bool {
  201. return false
  202. }
  203. func (db *sqlite3) IndexCheckSql(tableName, idxName string) (string, []interface{}) {
  204. args := []interface{}{idxName}
  205. return "SELECT name FROM sqlite_master WHERE type='index' and name = ?", args
  206. }
  207. func (db *sqlite3) TableCheckSql(tableName string) (string, []interface{}) {
  208. args := []interface{}{tableName}
  209. return "SELECT name FROM sqlite_master WHERE type='table' and name = ?", args
  210. }
  211. func (db *sqlite3) DropIndexSql(tableName string, index *core.Index) string {
  212. quote := db.Quote
  213. //var unique string
  214. var idxName string = index.Name
  215. if !strings.HasPrefix(idxName, "UQE_") &&
  216. !strings.HasPrefix(idxName, "IDX_") {
  217. if index.Type == core.UniqueType {
  218. idxName = fmt.Sprintf("UQE_%v_%v", tableName, index.Name)
  219. } else {
  220. idxName = fmt.Sprintf("IDX_%v_%v", tableName, index.Name)
  221. }
  222. }
  223. return fmt.Sprintf("DROP INDEX %v", quote(idxName))
  224. }
  225. /*func (db *sqlite3) ColumnCheckSql(tableName, colName string) (string, []interface{}) {
  226. args := []interface{}{tableName}
  227. sql := "SELECT name FROM sqlite_master WHERE type='table' and name = ? and ((sql like '%`" + colName + "`%') or (sql like '%[" + colName + "]%'))"
  228. return sql, args
  229. }*/
  230. func (db *sqlite3) IsColumnExist(tableName, colName string) (bool, error) {
  231. args := []interface{}{tableName}
  232. query := "SELECT name FROM sqlite_master WHERE type='table' and name = ? and ((sql like '%`" + colName + "`%') or (sql like '%[" + colName + "]%'))"
  233. rows, err := db.DB().Query(query, args...)
  234. if db.Logger != nil {
  235. db.Logger.Info("[sql]", query, args)
  236. }
  237. if err != nil {
  238. return false, err
  239. }
  240. defer rows.Close()
  241. if rows.Next() {
  242. return true, nil
  243. }
  244. return false, nil
  245. }
  246. func (db *sqlite3) GetColumns(tableName string) ([]string, map[string]*core.Column, error) {
  247. args := []interface{}{tableName}
  248. s := "SELECT sql FROM sqlite_master WHERE type='table' and name = ?"
  249. rows, err := db.DB().Query(s, args...)
  250. if db.Logger != nil {
  251. db.Logger.Info("[sql]", s, args)
  252. }
  253. if err != nil {
  254. return nil, nil, err
  255. }
  256. defer rows.Close()
  257. var name string
  258. for rows.Next() {
  259. err = rows.Scan(&name)
  260. if err != nil {
  261. return nil, nil, err
  262. }
  263. break
  264. }
  265. if name == "" {
  266. return nil, nil, errors.New("no table named " + tableName)
  267. }
  268. nStart := strings.Index(name, "(")
  269. nEnd := strings.LastIndex(name, ")")
  270. colCreates := strings.Split(name[nStart+1:nEnd], ",")
  271. cols := make(map[string]*core.Column)
  272. colSeq := make([]string, 0)
  273. for _, colStr := range colCreates {
  274. fields := strings.Fields(strings.TrimSpace(colStr))
  275. col := new(core.Column)
  276. col.Indexes = make(map[string]bool)
  277. col.Nullable = true
  278. col.DefaultIsEmpty = true
  279. for idx, field := range fields {
  280. if idx == 0 {
  281. col.Name = strings.Trim(field, "`[] ")
  282. continue
  283. } else if idx == 1 {
  284. col.SQLType = core.SQLType{field, 0, 0}
  285. }
  286. switch field {
  287. case "PRIMARY":
  288. col.IsPrimaryKey = true
  289. case "AUTOINCREMENT":
  290. col.IsAutoIncrement = true
  291. case "NULL":
  292. if fields[idx-1] == "NOT" {
  293. col.Nullable = false
  294. } else {
  295. col.Nullable = true
  296. }
  297. case "DEFAULT":
  298. col.Default = fields[idx+1]
  299. col.DefaultIsEmpty = false
  300. }
  301. }
  302. if !col.SQLType.IsNumeric() && !col.DefaultIsEmpty {
  303. col.Default = "'" + col.Default + "'"
  304. }
  305. cols[col.Name] = col
  306. colSeq = append(colSeq, col.Name)
  307. }
  308. return colSeq, cols, nil
  309. }
  310. func (db *sqlite3) GetTables() ([]*core.Table, error) {
  311. args := []interface{}{}
  312. s := "SELECT name FROM sqlite_master WHERE type='table'"
  313. rows, err := db.DB().Query(s, args...)
  314. if db.Logger != nil {
  315. db.Logger.Info("[sql]", s, args)
  316. }
  317. if err != nil {
  318. return nil, err
  319. }
  320. defer rows.Close()
  321. tables := make([]*core.Table, 0)
  322. for rows.Next() {
  323. table := core.NewEmptyTable()
  324. err = rows.Scan(&table.Name)
  325. if err != nil {
  326. return nil, err
  327. }
  328. if table.Name == "sqlite_sequence" {
  329. continue
  330. }
  331. tables = append(tables, table)
  332. }
  333. return tables, nil
  334. }
  335. func (db *sqlite3) GetIndexes(tableName string) (map[string]*core.Index, error) {
  336. args := []interface{}{tableName}
  337. s := "SELECT sql FROM sqlite_master WHERE type='index' and tbl_name = ?"
  338. rows, err := db.DB().Query(s, args...)
  339. if db.Logger != nil {
  340. db.Logger.Info("[sql]", s, args)
  341. }
  342. if err != nil {
  343. return nil, err
  344. }
  345. defer rows.Close()
  346. indexes := make(map[string]*core.Index, 0)
  347. for rows.Next() {
  348. var tmpSql sql.NullString
  349. err = rows.Scan(&tmpSql)
  350. if err != nil {
  351. return nil, err
  352. }
  353. if !tmpSql.Valid {
  354. continue
  355. }
  356. sql := tmpSql.String
  357. index := new(core.Index)
  358. nNStart := strings.Index(sql, "INDEX")
  359. nNEnd := strings.Index(sql, "ON")
  360. if nNStart == -1 || nNEnd == -1 {
  361. continue
  362. }
  363. indexName := strings.Trim(sql[nNStart+6:nNEnd], "` []")
  364. if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
  365. index.Name = indexName[5+len(tableName) : len(indexName)]
  366. } else {
  367. index.Name = indexName
  368. }
  369. if strings.HasPrefix(sql, "CREATE UNIQUE INDEX") {
  370. index.Type = core.UniqueType
  371. } else {
  372. index.Type = core.IndexType
  373. }
  374. nStart := strings.Index(sql, "(")
  375. nEnd := strings.Index(sql, ")")
  376. colIndexes := strings.Split(sql[nStart+1:nEnd], ",")
  377. index.Cols = make([]string, 0)
  378. for _, col := range colIndexes {
  379. index.Cols = append(index.Cols, strings.Trim(col, "` []"))
  380. }
  381. indexes[index.Name] = index
  382. }
  383. return indexes, nil
  384. }
  385. func (db *sqlite3) Filters() []core.Filter {
  386. return []core.Filter{&core.IdFilter{}}
  387. }