getIndexes returns all indexes schema of a collection. https://www.mongodb.com/docs/manual/reference/command/listIndexes/#output
(ctx context.Context, collection *mongo.Collection)
| 196 | // getIndexes returns all indexes schema of a collection. |
| 197 | // https://www.mongodb.com/docs/manual/reference/command/listIndexes/#output |
| 198 | func getIndexes(ctx context.Context, collection *mongo.Collection) ([]*storepb.IndexMetadata, error) { |
| 199 | indexCursor, err := collection.Indexes().List(ctx) |
| 200 | if err != nil { |
| 201 | return nil, errors.Wrap(err, "failed to list indexes") |
| 202 | } |
| 203 | indexMap := make(map[string]*storepb.IndexMetadata) |
| 204 | defer indexCursor.Close(ctx) |
| 205 | for indexCursor.Next(ctx) { |
| 206 | var indexInfo bson.M |
| 207 | if err := indexCursor.Decode(&indexInfo); err != nil { |
| 208 | return nil, errors.Wrap(err, "failed to decode index info") |
| 209 | } |
| 210 | name, ok := indexInfo["name"] |
| 211 | if !ok { |
| 212 | return nil, errors.New("cannot get index name from index info") |
| 213 | } |
| 214 | indexName, ok := name.(string) |
| 215 | if !ok { |
| 216 | return nil, errors.New("cannot cinvert index name to string") |
| 217 | } |
| 218 | key, ok := indexInfo["key"] |
| 219 | if !ok { |
| 220 | return nil, errors.New("cannot get index key from index info") |
| 221 | } |
| 222 | expression, err := json.Marshal(key) |
| 223 | if err != nil { |
| 224 | return nil, errors.Wrap(err, "cannot marshal index key to json") |
| 225 | } |
| 226 | unique := false |
| 227 | if u, ok := indexInfo["unique"]; ok { |
| 228 | unique, ok = u.(bool) |
| 229 | if !ok { |
| 230 | return nil, errors.New("cannot convert unique to bool") |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | if _, ok := indexMap[indexName]; !ok { |
| 235 | indexMap[indexName] = &storepb.IndexMetadata{ |
| 236 | Name: indexName, |
| 237 | Unique: unique, |
| 238 | } |
| 239 | } |
| 240 | indexMap[indexName].Expressions = append(indexMap[indexName].Expressions, string(expression)) |
| 241 | } |
| 242 | |
| 243 | var indexes []*storepb.IndexMetadata |
| 244 | var indexNames []string |
| 245 | for name := range indexMap { |
| 246 | indexNames = append(indexNames, name) |
| 247 | } |
| 248 | slices.Sort(indexNames) |
| 249 | for _, name := range indexNames { |
| 250 | indexes = append(indexes, indexMap[name]) |
| 251 | } |
| 252 | return indexes, nil |
| 253 | } |
| 254 | |
| 255 | func isSystemCollection(collectionName string) bool { |
no test coverage detected