dialect_sqlite3.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. //var unique string
  221. quote := db.Quote
  222. idxName := 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. db.LogSQL(query, args)
  245. rows, err := db.DB().Query(query, args...)
  246. if err != nil {
  247. return false, err
  248. }
  249. defer rows.Close()
  250. if rows.Next() {
  251. return true, nil
  252. }
  253. return false, nil
  254. }
  255. func (db *sqlite3) GetColumns(tableName string) ([]string, map[string]*core.Column, error) {
  256. args := []interface{}{tableName}
  257. s := "SELECT sql FROM sqlite_master WHERE type='table' and name = ?"
  258. db.LogSQL(s, args)
  259. rows, err := db.DB().Query(s, args...)
  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. reg := regexp.MustCompile(`[^\(,\)]*(\([^\(]*\))?`)
  278. colCreates := reg.FindAllString(name[nStart+1:nEnd], -1)
  279. cols := make(map[string]*core.Column)
  280. colSeq := make([]string, 0)
  281. for _, colStr := range colCreates {
  282. reg = regexp.MustCompile(`,\s`)
  283. colStr = reg.ReplaceAllString(colStr, ",")
  284. fields := strings.Fields(strings.TrimSpace(colStr))
  285. col := new(core.Column)
  286. col.Indexes = make(map[string]int)
  287. col.Nullable = true
  288. col.DefaultIsEmpty = true
  289. for idx, field := range fields {
  290. if idx == 0 {
  291. col.Name = strings.Trim(strings.Trim(field, "`[] "), `"`)
  292. continue
  293. } else if idx == 1 {
  294. col.SQLType = core.SQLType{Name: field, DefaultLength: 0, DefaultLength2: 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. db.LogSQL(s, args)
  324. rows, err := db.DB().Query(s, args...)
  325. if err != nil {
  326. return nil, err
  327. }
  328. defer rows.Close()
  329. tables := make([]*core.Table, 0)
  330. for rows.Next() {
  331. table := core.NewEmptyTable()
  332. err = rows.Scan(&table.Name)
  333. if err != nil {
  334. return nil, err
  335. }
  336. if table.Name == "sqlite_sequence" {
  337. continue
  338. }
  339. tables = append(tables, table)
  340. }
  341. return tables, nil
  342. }
  343. func (db *sqlite3) GetIndexes(tableName string) (map[string]*core.Index, error) {
  344. args := []interface{}{tableName}
  345. s := "SELECT sql FROM sqlite_master WHERE type='index' and tbl_name = ?"
  346. db.LogSQL(s, args)
  347. rows, err := db.DB().Query(s, args...)
  348. if err != nil {
  349. return nil, err
  350. }
  351. defer rows.Close()
  352. indexes := make(map[string]*core.Index, 0)
  353. for rows.Next() {
  354. var tmpSQL sql.NullString
  355. err = rows.Scan(&tmpSQL)
  356. if err != nil {
  357. return nil, err
  358. }
  359. if !tmpSQL.Valid {
  360. continue
  361. }
  362. sql := tmpSQL.String
  363. index := new(core.Index)
  364. nNStart := strings.Index(sql, "INDEX")
  365. nNEnd := strings.Index(sql, "ON")
  366. if nNStart == -1 || nNEnd == -1 {
  367. continue
  368. }
  369. indexName := strings.Trim(sql[nNStart+6:nNEnd], "` []")
  370. var isRegular bool
  371. if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
  372. index.Name = indexName[5+len(tableName):]
  373. isRegular = true
  374. } else {
  375. index.Name = indexName
  376. }
  377. if strings.HasPrefix(sql, "CREATE UNIQUE INDEX") {
  378. index.Type = core.UniqueType
  379. } else {
  380. index.Type = core.IndexType
  381. }
  382. nStart := strings.Index(sql, "(")
  383. nEnd := strings.Index(sql, ")")
  384. colIndexes := strings.Split(sql[nStart+1:nEnd], ",")
  385. index.Cols = make([]string, 0)
  386. for _, col := range colIndexes {
  387. index.Cols = append(index.Cols, strings.Trim(col, "` []"))
  388. }
  389. index.IsRegular = isRegular
  390. indexes[index.Name] = index
  391. }
  392. return indexes, nil
  393. }
  394. func (db *sqlite3) Filters() []core.Filter {
  395. return []core.Filter{&core.IdFilter{}}
  396. }
  397. type sqlite3Driver struct {
  398. }
  399. func (p *sqlite3Driver) Parse(driverName, dataSourceName string) (*core.Uri, error) {
  400. return &core.Uri{DbType: core.SQLITE, DbName: dataSourceName}, nil
  401. }