parser.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. package parser
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/tal-tech/go-zero/tools/goctl/model/sql/converter"
  6. "github.com/tal-tech/go-zero/tools/goctl/model/sql/model"
  7. "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
  8. "github.com/xwb1989/sqlparser"
  9. )
  10. const (
  11. _ = iota
  12. primary
  13. unique
  14. normal
  15. spatial
  16. )
  17. const timeImport = "time.Time"
  18. type (
  19. Table struct {
  20. Name stringx.String
  21. PrimaryKey Primary
  22. Fields []Field
  23. }
  24. Primary struct {
  25. Field
  26. AutoIncrement bool
  27. }
  28. Field struct {
  29. Name stringx.String
  30. DataBaseType string
  31. DataType string
  32. IsPrimaryKey bool
  33. IsUniqueKey bool
  34. Comment string
  35. }
  36. KeyType int
  37. )
  38. func Parse(ddl string) (*Table, error) {
  39. stmt, err := sqlparser.ParseStrictDDL(ddl)
  40. if err != nil {
  41. return nil, err
  42. }
  43. ddlStmt, ok := stmt.(*sqlparser.DDL)
  44. if !ok {
  45. return nil, errUnsupportDDL
  46. }
  47. action := ddlStmt.Action
  48. if action != sqlparser.CreateStr {
  49. return nil, fmt.Errorf("expected [CREATE] action,but found: %s", action)
  50. }
  51. tableName := ddlStmt.NewName.Name.String()
  52. tableSpec := ddlStmt.TableSpec
  53. if tableSpec == nil {
  54. return nil, errTableBodyNotFound
  55. }
  56. columns := tableSpec.Columns
  57. indexes := tableSpec.Indexes
  58. keyMap := make(map[string]KeyType)
  59. for _, index := range indexes {
  60. info := index.Info
  61. if info == nil {
  62. continue
  63. }
  64. if info.Primary {
  65. if len(index.Columns) > 1 {
  66. return nil, errPrimaryKey
  67. }
  68. keyMap[index.Columns[0].Column.String()] = primary
  69. continue
  70. }
  71. // can optimize
  72. if len(index.Columns) > 1 {
  73. continue
  74. }
  75. column := index.Columns[0]
  76. columnName := column.Column.String()
  77. camelColumnName := stringx.From(columnName).ToCamel()
  78. // by default, createTime|updateTime findOne is not used.
  79. if camelColumnName == "CreateTime" || camelColumnName == "UpdateTime" {
  80. continue
  81. }
  82. if info.Unique {
  83. keyMap[columnName] = unique
  84. } else if info.Spatial {
  85. keyMap[columnName] = spatial
  86. } else {
  87. keyMap[columnName] = normal
  88. }
  89. }
  90. var fields []Field
  91. var primaryKey Primary
  92. for _, column := range columns {
  93. if column == nil {
  94. continue
  95. }
  96. var comment string
  97. if column.Type.Comment != nil {
  98. comment = string(column.Type.Comment.Val)
  99. }
  100. var isDefaultNull = true
  101. if column.Type.NotNull {
  102. isDefaultNull = false
  103. } else {
  104. if column.Type.Default == nil {
  105. isDefaultNull = false
  106. } else if string(column.Type.Default.Val) != "null" {
  107. isDefaultNull = false
  108. }
  109. }
  110. dataType, err := converter.ConvertDataType(column.Type.Type, isDefaultNull)
  111. if err != nil {
  112. return nil, err
  113. }
  114. var field Field
  115. field.Name = stringx.From(column.Name.String())
  116. field.DataBaseType = column.Type.Type
  117. field.DataType = dataType
  118. field.Comment = comment
  119. key, ok := keyMap[column.Name.String()]
  120. if ok {
  121. field.IsPrimaryKey = key == primary
  122. field.IsUniqueKey = key == unique
  123. if field.IsPrimaryKey {
  124. primaryKey.Field = field
  125. if column.Type.Autoincrement {
  126. primaryKey.AutoIncrement = true
  127. }
  128. }
  129. }
  130. fields = append(fields, field)
  131. }
  132. return &Table{
  133. Name: stringx.From(tableName),
  134. PrimaryKey: primaryKey,
  135. Fields: fields,
  136. }, nil
  137. }
  138. func (t *Table) ContainsTime() bool {
  139. for _, item := range t.Fields {
  140. if item.DataType == timeImport {
  141. return true
  142. }
  143. }
  144. return false
  145. }
  146. func ConvertColumn(db, table string, in []*model.Column) (*Table, error) {
  147. var reply Table
  148. reply.Name = stringx.From(table)
  149. keyMap := make(map[string][]*model.Column)
  150. for _, column := range in {
  151. keyMap[column.Key] = append(keyMap[column.Key], column)
  152. }
  153. primaryColumns := keyMap["PRI"]
  154. if len(primaryColumns) == 0 {
  155. return nil, fmt.Errorf("database:%s, table %s: missing primary key", db, table)
  156. }
  157. if len(primaryColumns) > 1 {
  158. return nil, fmt.Errorf("database:%s, table %s: only one primary key expected", db, table)
  159. }
  160. primaryColumn := primaryColumns[0]
  161. isDefaultNull := primaryColumn.ColumnDefault == nil && primaryColumn.IsNullAble == "YES"
  162. primaryFt, err := converter.ConvertDataType(primaryColumn.DataType, isDefaultNull)
  163. if err != nil {
  164. return nil, err
  165. }
  166. primaryField := Field{
  167. Name: stringx.From(primaryColumn.Name),
  168. DataBaseType: primaryColumn.DataType,
  169. DataType: primaryFt,
  170. IsUniqueKey: true,
  171. IsPrimaryKey: true,
  172. Comment: primaryColumn.Comment,
  173. }
  174. reply.PrimaryKey = Primary{
  175. Field: primaryField,
  176. AutoIncrement: strings.Contains(primaryColumn.Extra, "auto_increment"),
  177. }
  178. for key, columns := range keyMap {
  179. for _, item := range columns {
  180. isColumnDefaultNull := item.ColumnDefault == nil && item.IsNullAble == "YES"
  181. dt, err := converter.ConvertDataType(item.DataType, isColumnDefaultNull)
  182. if err != nil {
  183. return nil, err
  184. }
  185. f := Field{
  186. Name: stringx.From(item.Name),
  187. DataBaseType: item.DataType,
  188. DataType: dt,
  189. IsPrimaryKey: primaryColumn.Name == item.Name,
  190. Comment: item.Comment,
  191. }
  192. if key == "UNI" {
  193. f.IsUniqueKey = true
  194. }
  195. reply.Fields = append(reply.Fields, f)
  196. }
  197. }
  198. return &reply, nil
  199. }