parser.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 sqlchemy
  15. import (
  16. "fmt"
  17. "reflect"
  18. "yunion.io/x/pkg/util/reflectutils"
  19. )
  20. func (table *STableSpec) structField2ColumnSpec(field *reflectutils.SStructFieldValue) IColumnSpec {
  21. fieldname := field.Info.MarshalName()
  22. tagmap := field.Info.Tags
  23. if _, ok := tagmap[TAG_IGNORE]; ok {
  24. return nil
  25. }
  26. db := table.Database()
  27. if db == nil {
  28. panic("structField2ColumnSpec: empty database")
  29. }
  30. if db.backend == nil {
  31. panic("structField2ColumnSpec: empty backend")
  32. }
  33. fieldType := field.Value.Type()
  34. var retCol = db.backend.GetColumnSpecByFieldType(table, fieldType, fieldname, tagmap, false)
  35. if retCol == nil && fieldType.Kind() == reflect.Ptr {
  36. retCol = db.backend.GetColumnSpecByFieldType(table, fieldType.Elem(), fieldname, tagmap, true)
  37. }
  38. if retCol == nil {
  39. panic(fmt.Sprintf("unsupported colume %s data type %s", fieldname, fieldType.Name()))
  40. }
  41. return retCol
  42. }
  43. func (table *STableSpec) struct2TableSpec(sv reflect.Value) {
  44. fields := reflectutils.FetchStructFieldValueSet(sv)
  45. autoIncCnt := 0
  46. tmpCols := make([]IColumnSpec, 0)
  47. for i := 0; i < len(fields); i++ {
  48. column := table.structField2ColumnSpec(&fields[i])
  49. if column != nil {
  50. if column.IsAutoIncrement() {
  51. autoIncCnt++
  52. if autoIncCnt > 1 {
  53. panic(fmt.Sprintf("Table %s contains multiple autoincremental columns!!", table.name))
  54. }
  55. }
  56. if column.IsIndex() {
  57. table.AddIndex(column.IsUnique(), column.Name())
  58. }
  59. tmpCols = append(tmpCols, column)
  60. }
  61. }
  62. // make column assignment atomic
  63. table._columns = tmpCols
  64. }