dialect_sqlite3.go 12 KB

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