sqlite.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package sqlite
  15. import (
  16. "fmt"
  17. "reflect"
  18. "strings"
  19. _ "github.com/mattn/go-sqlite3"
  20. "yunion.io/x/pkg/errors"
  21. "yunion.io/x/pkg/gotypes"
  22. "yunion.io/x/pkg/tristate"
  23. "yunion.io/x/sqlchemy"
  24. )
  25. func init() {
  26. sqlchemy.RegisterBackend(&SSqliteBackend{})
  27. }
  28. type SSqliteBackend struct {
  29. sqlchemy.SBaseBackend
  30. }
  31. func (sqlite *SSqliteBackend) Name() sqlchemy.DBBackendName {
  32. return sqlchemy.SQLiteBackend
  33. }
  34. // CanUpdate returns wether the backend supports update
  35. func (sqlite *SSqliteBackend) CanUpdate() bool {
  36. return true
  37. }
  38. // CanInsert returns wether the backend supports Insert
  39. func (sqlite *SSqliteBackend) CanInsert() bool {
  40. return true
  41. }
  42. // CanInsertOrUpdate returns weather the backend supports InsertOrUpdate
  43. func (sqlite *SSqliteBackend) CanInsertOrUpdate() bool {
  44. return true
  45. }
  46. func (sqlite *SSqliteBackend) CurrentUTCTimeStampString() string {
  47. return "DATETIME('now')"
  48. }
  49. func (sqlite *SSqliteBackend) CurrentTimeStampString() string {
  50. return "DATETIME('now', 'localtime')"
  51. }
  52. func (sqlite *SSqliteBackend) DropIndexSQLTemplate() string {
  53. return "DROP INDEX IF EXISTS `{{ .Table }}`.`{{ .Index }}`"
  54. }
  55. func (sqlite *SSqliteBackend) InsertOrUpdateSQLTemplate() string {
  56. return "INSERT INTO `{{ .Table }}` ({{ .Columns }}) VALUES ({{ .Values }}) ON CONFLICT({{ .PrimaryKeys }}) DO UPDATE SET {{ .SetValues }}"
  57. }
  58. func (sqlite *SSqliteBackend) GetTableSQL() string {
  59. return "SELECT name FROM sqlite_master WHERE type='table'"
  60. }
  61. func (sqlite *SSqliteBackend) IsSupportIndexAndContraints() bool {
  62. return true
  63. }
  64. func (sqlite *SSqliteBackend) GetCreateSQLs(ts sqlchemy.ITableSpec) []string {
  65. cols := make([]string, 0)
  66. primaries := make([]string, 0)
  67. for _, c := range ts.Columns() {
  68. cols = append(cols, c.DefinitionString())
  69. if c.IsPrimary() && !c.IsAutoIncrement() {
  70. primaries = append(primaries, fmt.Sprintf("`%s`", c.Name()))
  71. }
  72. }
  73. if len(primaries) > 0 {
  74. cols = append(cols, fmt.Sprintf("PRIMARY KEY (%s)", strings.Join(primaries, ", ")))
  75. }
  76. ret := []string{
  77. "PRAGMA encoding=\"UTF-8\"",
  78. fmt.Sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n%s\n)", ts.Name(), strings.Join(cols, ",\n")),
  79. }
  80. for _, idx := range ts.Indexes() {
  81. ret = append(ret, createIndexSQL(ts, idx))
  82. }
  83. return ret
  84. }
  85. func (sqlite *SSqliteBackend) FetchIndexesAndConstraints(ts sqlchemy.ITableSpec) ([]sqlchemy.STableIndex, []sqlchemy.STableConstraint, error) {
  86. sql := fmt.Sprintf("SELECT `name`, `sql` FROM `sqlite_master` WHERE `tbl_name`='%s' AND `type`='index' AND `sql`!=''", ts.Name())
  87. query := ts.Database().NewRawQuery(sql, "name", "sql")
  88. results := make([]sSqliteTableInfo, 0)
  89. err := query.All(&results)
  90. if err != nil {
  91. return nil, nil, errors.Wrapf(err, "Raw Query Scan %s", sql)
  92. }
  93. indexes := make([]sqlchemy.STableIndex, 0)
  94. for i := range results {
  95. ti, err := results[i].parseTableIndex(ts)
  96. if err != nil {
  97. return nil, nil, errors.Wrapf(err, "parseTableIndex fail %s", results[i].Sql)
  98. }
  99. indexes = append(indexes, ti)
  100. }
  101. return indexes, nil, nil
  102. }
  103. func (sqlite *SSqliteBackend) FetchTableColumnSpecs(ts sqlchemy.ITableSpec) ([]sqlchemy.IColumnSpec, error) {
  104. sql := fmt.Sprintf("PRAGMA table_info(`%s`);", ts.Name())
  105. query := ts.Database().NewRawQuery(sql, "cid", "name", "type", "notnull", "dflt_value", "pk")
  106. infos := make([]sSqlColumnInfo, 0)
  107. err := query.All(&infos)
  108. if err != nil {
  109. return nil, err
  110. }
  111. specs := make([]sqlchemy.IColumnSpec, 0)
  112. // find out integer primary key
  113. var primaryCol sqlchemy.IColumnSpec
  114. var primaryCount int
  115. for _, info := range infos {
  116. spec := info.toColumnSpec()
  117. if spec.IsPrimary() {
  118. primaryCol = spec
  119. primaryCount++
  120. }
  121. specs = append(specs, spec)
  122. }
  123. if primaryCount == 1 {
  124. if intc, ok := primaryCol.(*SIntegerColumn); ok {
  125. intc.isAutoIncrement = true
  126. }
  127. }
  128. return specs, nil
  129. }
  130. func (sqlite *SSqliteBackend) GetColumnSpecByFieldType(table *sqlchemy.STableSpec, fieldType reflect.Type, fieldname string, tagmap map[string]string, isPointer bool) sqlchemy.IColumnSpec {
  131. switch fieldType {
  132. case tristate.TriStateType:
  133. col := NewTristateColumn(table.Name(), fieldname, tagmap, isPointer)
  134. return &col
  135. case gotypes.TimeType:
  136. col := NewDateTimeColumn(fieldname, tagmap, isPointer)
  137. return &col
  138. }
  139. switch fieldType.Kind() {
  140. case reflect.String:
  141. col := NewTextColumn(fieldname, tagmap, isPointer)
  142. return &col
  143. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  144. col := NewIntegerColumn(fieldname, tagmap, isPointer)
  145. return &col
  146. case reflect.Bool:
  147. col := NewBooleanColumn(fieldname, tagmap, isPointer)
  148. return &col
  149. case reflect.Float32, reflect.Float64:
  150. col := NewFloatColumn(fieldname, tagmap, isPointer)
  151. return &col
  152. case reflect.Map, reflect.Slice:
  153. col := NewCompoundColumn(fieldname, tagmap, isPointer)
  154. return &col
  155. }
  156. if fieldType.Implements(gotypes.ISerializableType) {
  157. col := NewCompoundColumn(fieldname, tagmap, isPointer)
  158. return &col
  159. }
  160. return nil
  161. }