columninfo.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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 dameng
  15. import (
  16. "bytes"
  17. "database/sql"
  18. "encoding/binary"
  19. "fmt"
  20. "strings"
  21. "yunion.io/x/log"
  22. "yunion.io/x/pkg/errors"
  23. "yunion.io/x/sqlchemy"
  24. )
  25. // COLUMN_NAME, DATA_TYPE, NULLABLE, DATA_LENGTH, CHARACTER_SET_NAME, DATA_DEFAULT
  26. type sSqlColumnInfo struct {
  27. TableName string `json:"TABLE_NAME"`
  28. ColumnName string `json:"COLUMN_NAME"`
  29. DataType string `json:"DATA_TYPE"`
  30. Nullable string `json:"NULLABLE"`
  31. DataLength int `json:"DATA_LENGTH"`
  32. DataPrecision int `json:"DATA_PRECISION"`
  33. DataScale int `json:"DATA_SCALE"`
  34. CharacterSetName string `json:"CHARACTER_SET_NAME"`
  35. DataDefault string `json:"DATA_DEFAULT"`
  36. IsPrimary bool `json:"is_primary"`
  37. IsAutoIncrement bool `json:"is_auto_increment"`
  38. AutoIncrementOffset uint64 `json:"auto_increment_offset"`
  39. AutoIncrementStep uint64 `json:"auto_increment_step"`
  40. }
  41. func fetchTableColInfo(ts sqlchemy.ITableSpec) (map[string]*sSqlColumnInfo, error) {
  42. sqlStr := fmt.Sprintf("SELECT COLUMN_NAME, DATA_TYPE, NULLABLE, DATA_LENGTH, DATA_PRECISION, DATA_SCALE, CHARACTER_SET_NAME, DATA_DEFAULT FROM USER_TAB_COLUMNS WHERE Table_Name='%s'", ts.Name())
  43. query := ts.Database().NewRawQuery(sqlStr, "column_name", "data_type", "nullable", "data_length", "data_precision", "data_scale", "character_set_name", "data_default")
  44. infos := make([]sSqlColumnInfo, 0)
  45. err := query.All(&infos)
  46. if err != nil {
  47. return nil, errors.Wrap(err, "query")
  48. }
  49. ret := make(map[string]*sSqlColumnInfo)
  50. for i := range infos {
  51. infos[i].TableName = ts.Name()
  52. infos[i].ColumnName = strings.ToLower(infos[i].ColumnName)
  53. ret[infos[i].ColumnName] = &infos[i]
  54. }
  55. indexes, err := fetchTableIndexes(ts)
  56. if err != nil {
  57. return nil, errors.Wrap(err, "fetchTableIndexes")
  58. }
  59. for _, idx := range indexes {
  60. if idx.isPrimary {
  61. for _, col := range idx.colnames {
  62. ret[col].IsPrimary = true
  63. }
  64. break
  65. }
  66. }
  67. autoIncInfo, err := fetchTableAutoIncrementCol(ts)
  68. if err != nil {
  69. return nil, errors.Wrap(err, "fetchTableAutoIncrementCol")
  70. } else if autoIncInfo != nil {
  71. ret[autoIncInfo.Name].IsAutoIncrement = true
  72. ret[autoIncInfo.Name].AutoIncrementOffset = autoIncInfo.Offset
  73. ret[autoIncInfo.Name].AutoIncrementStep = autoIncInfo.Step
  74. }
  75. return ret, nil
  76. }
  77. type sDamengTableIndex struct {
  78. isPrimary bool
  79. indexName string
  80. colnames []string
  81. }
  82. func fetchTableIndexes(ts sqlchemy.ITableSpec) (map[string]sDamengTableIndex, error) {
  83. type sIndexInfo struct {
  84. ColumnName string `json:"COLUMN_NAME"`
  85. IndexName string `json:"INDEX_NAME"`
  86. ConstraintType string `json:"CONSTRAINT_TYPE"`
  87. }
  88. sqlStr := fmt.Sprintf("SELECT a.COLUMN_NAME, a.INDEX_NAME, b.CONSTRAINT_TYPE FROM USER_IND_COLUMNS a LEFT JOIN USER_CONSTRAINTS b ON a.INDEX_NAME=b.INDEX_NAME WHERE a.TABLE_NAME='%s'", ts.Name())
  89. query := ts.Database().NewRawQuery(sqlStr, "column_name", "index_name", "constraint_type")
  90. infos := make([]sIndexInfo, 0)
  91. err := query.All(&infos)
  92. if err != nil {
  93. return nil, err
  94. }
  95. ret := make(map[string]sDamengTableIndex)
  96. for _, info := range infos {
  97. info.IndexName = strings.ToLower(info.IndexName)
  98. info.ColumnName = strings.ToLower(info.ColumnName)
  99. if idx, ok := ret[info.IndexName]; ok {
  100. idx.colnames = append(idx.colnames, info.ColumnName)
  101. ret[info.IndexName] = idx
  102. } else {
  103. ret[info.IndexName] = sDamengTableIndex{
  104. isPrimary: info.ConstraintType == "P",
  105. indexName: info.IndexName,
  106. colnames: []string{info.ColumnName},
  107. }
  108. }
  109. }
  110. return ret, nil
  111. }
  112. func fetchTableAutoIncrementCol(ts sqlchemy.ITableSpec) (*sDamengAutoIncrementInfo, error) {
  113. sqlStr := fmt.Sprintf("SELECT a.NAME, c.INFO6 from SYSCOLUMNS a, SYSOBJECTS c WHERE a.INFO2 & 0x01 = 0x01 AND a.ID=c.ID and c.NAME='%s' AND c.SCHID=CURRENT_SCHID", ts.Name())
  114. query := ts.Database().NewRawQuery(sqlStr, "name", "info6")
  115. row := query.Row()
  116. name := ""
  117. info6 := make([]byte, 0)
  118. err := row.Scan(&name, &info6)
  119. if err != nil {
  120. if errors.Cause(err) == sql.ErrNoRows {
  121. return nil, nil
  122. } else {
  123. return nil, errors.Wrap(err, "Query")
  124. }
  125. }
  126. return decodeInfo6(name, info6)
  127. }
  128. type sDamengAutoIncrementInfo struct {
  129. Name string
  130. Offset uint64
  131. Step uint64
  132. Dummy uint64
  133. }
  134. func decodeInfo6(name string, binHex []byte) (*sDamengAutoIncrementInfo, error) {
  135. buf := bytes.NewReader(binHex)
  136. var pi [3]uint64
  137. for i := range pi {
  138. err := binary.Read(buf, binary.LittleEndian, &pi[i])
  139. if err != nil {
  140. return nil, errors.Wrap(err, "binary.LittleEndian.Read")
  141. }
  142. }
  143. return &sDamengAutoIncrementInfo{
  144. Name: strings.ToLower(name),
  145. Offset: pi[0],
  146. Step: pi[1],
  147. Dummy: pi[2],
  148. }, nil
  149. }
  150. func (info *sSqlColumnInfo) toColumnSpec() sqlchemy.IColumnSpec {
  151. tagmap := make(map[string]string)
  152. typeStr := strings.ToUpper(info.DataType)
  153. if info.Nullable == "Y" {
  154. tagmap[sqlchemy.TAG_NULLABLE] = "true"
  155. } else {
  156. tagmap[sqlchemy.TAG_NULLABLE] = "false"
  157. }
  158. if info.IsPrimary {
  159. tagmap[sqlchemy.TAG_PRIMARY] = "true"
  160. } else {
  161. tagmap[sqlchemy.TAG_PRIMARY] = "false"
  162. }
  163. if info.DataDefault != "NULL" && len(info.DataDefault) > 0 {
  164. tagmap[sqlchemy.TAG_DEFAULT] = info.DataDefault
  165. }
  166. if typeStr == "VARCHAR" || typeStr == "CHAR" || typeStr == "CHARACTER" {
  167. tagmap[sqlchemy.TAG_WIDTH] = fmt.Sprintf("%d", info.DataLength)
  168. if val, ok := tagmap[sqlchemy.TAG_DEFAULT]; ok {
  169. tagmap[sqlchemy.TAG_DEFAULT] = strings.Trim(val, "'\"")
  170. }
  171. c := NewTextColumn(info.ColumnName, typeStr, tagmap, false)
  172. return &c
  173. } else if typeStr == "TEXT" || typeStr == "LONGVARCHAR" || typeStr == "CLOB" || typeStr == "BLOB" {
  174. if val, ok := tagmap[sqlchemy.TAG_DEFAULT]; ok {
  175. tagmap[sqlchemy.TAG_DEFAULT] = strings.Trim(val, "'\"")
  176. }
  177. c := NewTextColumn(info.ColumnName, typeStr, tagmap, false)
  178. return &c
  179. } else if strings.HasSuffix(typeStr, "INT") {
  180. if val, ok := tagmap[sqlchemy.TAG_DEFAULT]; ok {
  181. tagmap[sqlchemy.TAG_DEFAULT] = strings.Trim(val, "()")
  182. }
  183. if typeStr == "TINYINT" {
  184. if info.Nullable == "Y" {
  185. c := NewTristateColumn(info.TableName, info.ColumnName, tagmap, false)
  186. return &c
  187. } else {
  188. if info.DataDefault == "1" {
  189. c := NewBooleanColumn(info.ColumnName, tagmap, true)
  190. return &c
  191. } else {
  192. c := NewBooleanColumn(info.ColumnName, tagmap, false)
  193. return &c
  194. }
  195. }
  196. } else {
  197. if info.IsAutoIncrement {
  198. if info.AutoIncrementOffset > 0 {
  199. tagmap[sqlchemy.TAG_AUTOINCREMENT] = fmt.Sprintf("%d", info.AutoIncrementOffset)
  200. } else {
  201. tagmap[sqlchemy.TAG_AUTOINCREMENT] = "true"
  202. }
  203. }
  204. c := NewIntegerColumn(info.ColumnName, typeStr, tagmap, false)
  205. return &c
  206. }
  207. } else if typeStr == "REAL" || typeStr == "FLOAT" || typeStr == "DOUBLE" || typeStr == "DOUBLE PRECISION" {
  208. if val, ok := tagmap[sqlchemy.TAG_DEFAULT]; ok {
  209. tagmap[sqlchemy.TAG_DEFAULT] = strings.Trim(val, "()")
  210. }
  211. c := NewFloatColumn(info.ColumnName, typeStr, tagmap, false)
  212. return &c
  213. } else if typeStr == "NUMERIC" || typeStr == "NUMBER" || typeStr == "DECIMAL" || typeStr == "DEC" {
  214. if val, ok := tagmap[sqlchemy.TAG_DEFAULT]; ok {
  215. tagmap[sqlchemy.TAG_DEFAULT] = strings.Trim(val, "()")
  216. }
  217. tagmap[sqlchemy.TAG_WIDTH] = fmt.Sprintf("%d", info.DataPrecision)
  218. tagmap[sqlchemy.TAG_PRECISION] = fmt.Sprintf("%d", info.DataScale)
  219. c := NewDecimalColumn(info.ColumnName, tagmap, false)
  220. return &c
  221. } else if typeStr == "TIMESTAMP" || typeStr == "DATATIME" {
  222. if val, ok := tagmap[sqlchemy.TAG_DEFAULT]; ok {
  223. tagmap[sqlchemy.TAG_DEFAULT] = strings.Trim(val, "'\"")
  224. }
  225. c := NewDateTimeColumn(info.ColumnName, tagmap, false)
  226. return &c
  227. } else if typeStr == "TIME" || typeStr == "DATE" {
  228. if val, ok := tagmap[sqlchemy.TAG_DEFAULT]; ok {
  229. tagmap[sqlchemy.TAG_DEFAULT] = strings.Trim(val, "'\"")
  230. }
  231. c := NewTimeTypeColumn(info.ColumnName, typeStr, tagmap, false)
  232. return &c
  233. } else {
  234. log.Errorf("unsupported column data type %s", typeStr)
  235. return nil
  236. }
  237. }