sqlite3_dialect.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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) ColumnCheckSql(tableName, colName string) (string, []interface{}) {
  233. args := []interface{}{tableName}
  234. sql := "SELECT name FROM sqlite_master WHERE type='table' and name = ? and ((sql like '%`" + colName + "`%') or (sql like '%[" + colName + "]%'))"
  235. return sql, args
  236. }*/
  237. func (db *sqlite3) IsColumnExist(tableName, colName string) (bool, error) {
  238. args := []interface{}{tableName}
  239. query := "SELECT name FROM sqlite_master WHERE type='table' and name = ? and ((sql like '%`" + colName + "`%') or (sql like '%[" + colName + "]%'))"
  240. rows, err := db.DB().Query(query, args...)
  241. if db.Logger != nil {
  242. db.Logger.Info("[sql]", query, args)
  243. }
  244. if err != nil {
  245. return false, err
  246. }
  247. defer rows.Close()
  248. if rows.Next() {
  249. return true, nil
  250. }
  251. return false, nil
  252. }
  253. func (db *sqlite3) GetColumns(tableName string) ([]string, map[string]*core.Column, error) {
  254. args := []interface{}{tableName}
  255. s := "SELECT sql FROM sqlite_master WHERE type='table' and name = ?"
  256. rows, err := db.DB().Query(s, args...)
  257. if db.Logger != nil {
  258. db.Logger.Info("[sql]", s, args)
  259. }
  260. if err != nil {
  261. return nil, nil, err
  262. }
  263. defer rows.Close()
  264. var name string
  265. for rows.Next() {
  266. err = rows.Scan(&name)
  267. if err != nil {
  268. return nil, nil, err
  269. }
  270. break
  271. }
  272. if name == "" {
  273. return nil, nil, errors.New("no table named " + tableName)
  274. }
  275. nStart := strings.Index(name, "(")
  276. nEnd := strings.LastIndex(name, ")")
  277. colCreates := strings.Split(name[nStart+1:nEnd], ",")
  278. cols := make(map[string]*core.Column)
  279. colSeq := make([]string, 0)
  280. for _, colStr := range colCreates {
  281. fields := strings.Fields(strings.TrimSpace(colStr))
  282. col := new(core.Column)
  283. col.Indexes = make(map[string]bool)
  284. col.Nullable = true
  285. col.DefaultIsEmpty = true
  286. for idx, field := range fields {
  287. if idx == 0 {
  288. col.Name = strings.Trim(field, "`[] ")
  289. continue
  290. } else if idx == 1 {
  291. col.SQLType = core.SQLType{field, 0, 0}
  292. }
  293. switch field {
  294. case "PRIMARY":
  295. col.IsPrimaryKey = true
  296. case "AUTOINCREMENT":
  297. col.IsAutoIncrement = true
  298. case "NULL":
  299. if fields[idx-1] == "NOT" {
  300. col.Nullable = false
  301. } else {
  302. col.Nullable = true
  303. }
  304. case "DEFAULT":
  305. col.Default = fields[idx+1]
  306. col.DefaultIsEmpty = false
  307. }
  308. }
  309. if !col.SQLType.IsNumeric() && !col.DefaultIsEmpty {
  310. col.Default = "'" + col.Default + "'"
  311. }
  312. cols[col.Name] = col
  313. colSeq = append(colSeq, col.Name)
  314. }
  315. return colSeq, cols, nil
  316. }
  317. func (db *sqlite3) GetTables() ([]*core.Table, error) {
  318. args := []interface{}{}
  319. s := "SELECT name FROM sqlite_master WHERE type='table'"
  320. rows, err := db.DB().Query(s, args...)
  321. if db.Logger != nil {
  322. db.Logger.Info("[sql]", s, args)
  323. }
  324. if err != nil {
  325. return nil, err
  326. }
  327. defer rows.Close()
  328. tables := make([]*core.Table, 0)
  329. for rows.Next() {
  330. table := core.NewEmptyTable()
  331. err = rows.Scan(&table.Name)
  332. if err != nil {
  333. return nil, err
  334. }
  335. if table.Name == "sqlite_sequence" {
  336. continue
  337. }
  338. tables = append(tables, table)
  339. }
  340. return tables, nil
  341. }
  342. func (db *sqlite3) GetIndexes(tableName string) (map[string]*core.Index, error) {
  343. args := []interface{}{tableName}
  344. s := "SELECT sql FROM sqlite_master WHERE type='index' and tbl_name = ?"
  345. rows, err := db.DB().Query(s, args...)
  346. if db.Logger != nil {
  347. db.Logger.Info("[sql]", s, args)
  348. }
  349. if err != nil {
  350. return nil, err
  351. }
  352. defer rows.Close()
  353. indexes := make(map[string]*core.Index, 0)
  354. for rows.Next() {
  355. var tmpSql sql.NullString
  356. err = rows.Scan(&tmpSql)
  357. if err != nil {
  358. return nil, err
  359. }
  360. if !tmpSql.Valid {
  361. continue
  362. }
  363. sql := tmpSql.String
  364. index := new(core.Index)
  365. nNStart := strings.Index(sql, "INDEX")
  366. nNEnd := strings.Index(sql, "ON")
  367. if nNStart == -1 || nNEnd == -1 {
  368. continue
  369. }
  370. indexName := strings.Trim(sql[nNStart+6:nNEnd], "` []")
  371. if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
  372. index.Name = indexName[5+len(tableName) : len(indexName)]
  373. } else {
  374. index.Name = indexName
  375. }
  376. if strings.HasPrefix(sql, "CREATE UNIQUE INDEX") {
  377. index.Type = core.UniqueType
  378. } else {
  379. index.Type = core.IndexType
  380. }
  381. nStart := strings.Index(sql, "(")
  382. nEnd := strings.Index(sql, ")")
  383. colIndexes := strings.Split(sql[nStart+1:nEnd], ",")
  384. index.Cols = make([]string, 0)
  385. for _, col := range colIndexes {
  386. index.Cols = append(index.Cols, strings.Trim(col, "` []"))
  387. }
  388. indexes[index.Name] = index
  389. }
  390. return indexes, nil
  391. }
  392. func (db *sqlite3) Filters() []core.Filter {
  393. return []core.Filter{&core.IdFilter{}}
  394. }