github.com/octohelm/storage@v0.0.0-20240516030302-1ac2cc1ea347/pkg/sqlbuilder/def_key_collection.go (about) 1 package sqlbuilder 2 3 import ( 4 "fmt" 5 "strings" 6 ) 7 8 type KeyCollection interface { 9 Of(t Table) KeyCollection 10 11 K(name string) Key 12 RangeKey(func(k Key, i int) bool) 13 Keys(names ...string) KeyCollection 14 Len() int 15 } 16 17 type KeyCollectionManager interface { 18 AddKey(keys ...Key) 19 } 20 21 type keys struct { 22 l []Key 23 } 24 25 func (ks *keys) Len() int { 26 if ks == nil { 27 return 0 28 } 29 return len(ks.l) 30 } 31 32 func (ks *keys) K(keyName string) Key { 33 keyName = strings.ToLower(keyName) 34 for i := range ks.l { 35 k := ks.l[i] 36 if keyName == k.Name() { 37 return k 38 } 39 } 40 return nil 41 } 42 43 func (ks *keys) AddKey(nextKeys ...Key) { 44 for i := range nextKeys { 45 k := nextKeys[i] 46 if k == nil { 47 continue 48 } 49 ks.l = append(ks.l, k) 50 } 51 } 52 53 func (ks *keys) Of(newTable Table) KeyCollection { 54 newKeys := &keys{} 55 for i := range ks.l { 56 newKeys.AddKey(ks.l[i].Of(newTable)) 57 } 58 return newKeys 59 } 60 61 func (ks *keys) Keys(names ...string) KeyCollection { 62 if len(names) == 0 { 63 return &keys{ 64 l: ks.l, 65 } 66 } 67 68 newCols := &keys{} 69 for _, indexName := range names { 70 col := ks.K(indexName) 71 if col == nil { 72 panic(fmt.Errorf("unknown index %s", indexName)) 73 } 74 newCols.AddKey(col) 75 } 76 return newCols 77 } 78 79 func (ks *keys) RangeKey(cb func(col Key, idx int) bool) { 80 for i := range ks.l { 81 if !cb(ks.l[i], i) { 82 break 83 } 84 } 85 }