github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/modelgen/util.go (about) 1 package modelgen 2 3 import ( 4 "go/types" 5 "reflect" 6 "regexp" 7 "strings" 8 9 "github.com/machinefi/w3bstream/pkg/depends/kit/sqlx/builder" 10 ) 11 12 func forEachStructField(st *types.Struct, each func(v *types.Var, name, tag string)) { 13 for i := 0; i < st.NumFields(); i++ { 14 f := st.Field(i) 15 if !f.Exported() { 16 continue 17 } 18 tag, exists := reflect.StructTag(st.Tag(i)).Lookup("db") 19 if exists && tag != "-" { 20 each(f, builder.GetColumnName(f.Name(), tag), tag) 21 continue 22 } 23 if f.Anonymous() { 24 if embed, ok := f.Type().Underlying().(*types.Struct); ok { 25 forEachStructField(embed, each) 26 } 27 } 28 } 29 } 30 31 var regexpRelAnnotate = regexp.MustCompile(`@rel ([^\n]+)`) 32 33 func parseColRelFromDoc(doc string) (string, []string) { 34 others := make([]string, 0) 35 rel := "" 36 for _, line := range strings.Split(doc, "\n") { 37 if len(line) == 0 { 38 continue 39 } 40 matches := regexpRelAnnotate.FindAllStringSubmatch(line, 1) 41 if matches == nil { 42 others = append(others, line) 43 continue 44 } 45 if len(matches) == 1 { 46 rel = matches[0][1] 47 } 48 } 49 return rel, others 50 } 51 52 var regexpDefAnnotate = regexp.MustCompile(`@def ([^\n]+)`) 53 54 func parseKeysFromDoc(doc string) (*Keys, []string) { 55 keys := &Keys{} 56 others := make([]string, 0) 57 58 for _, line := range strings.Split(doc, "\n") { 59 if len(line) == 0 { 60 continue 61 } 62 63 matches := regexpDefAnnotate.FindAllStringSubmatch(line, -1) 64 65 if matches == nil { 66 others = append(others, line) 67 continue 68 } 69 70 for _, sub := range matches { 71 if len(sub) == 2 { 72 def := builder.ParseIndexDefine(sub[1]) 73 switch def.Kind { 74 case "primary": 75 keys.Primary = def.ToDefs() 76 case "unique_index": 77 if keys.UniqueIndexes == nil { 78 keys.UniqueIndexes = builder.Indexes{} 79 } 80 keys.UniqueIndexes[def.ID()] = def.ToDefs() 81 case "index": 82 if keys.Indexes == nil { 83 keys.Indexes = builder.Indexes{} 84 } 85 keys.Indexes[def.ID()] = def.ToDefs() 86 } 87 } 88 } 89 } 90 91 return keys, others 92 } 93 94 func uniqueStrings(lst []string) (res []string) { 95 m := make(map[string]bool) 96 for _, s := range lst { 97 m[s] = true 98 } 99 for _, s := range lst { 100 if _, ok := m[s]; ok { 101 delete(m, s) 102 res = append(res, s) 103 } 104 } 105 return 106 } 107 108 func filterStrings(lst []string, chk func(s string, i int) bool) []string { 109 left, _ := partedStrings(lst, chk) 110 return left 111 } 112 113 func partedStrings(lst []string, chk func(s string, i int) bool) ([]string, []string) { 114 newLs, newRs := make([]string, 0), make([]string, 0) 115 for i, s := range lst { 116 if chk(s, i) { 117 newLs = append(newLs, s) 118 } else { 119 newRs = append(newRs, s) 120 } 121 } 122 return newLs, newRs 123 }