| 373 | } |
| 374 | |
| 375 | func (adh *AdminHandler) addSearchAttributesSQL( |
| 376 | ctx context.Context, |
| 377 | request *adminservice.AddSearchAttributesRequest, |
| 378 | currentSearchAttributes searchattribute.NameTypeMap, |
| 379 | ) error { |
| 380 | _, client, err := adh.clientFactory.NewLocalFrontendClientWithTimeout( |
| 381 | frontend.DefaultTimeout, |
| 382 | frontend.DefaultLongPollTimeout, |
| 383 | ) |
| 384 | if err != nil { |
| 385 | return serviceerror.NewUnavailablef(errUnableToCreateFrontendClientMessage, err) |
| 386 | } |
| 387 | |
| 388 | nsName := request.GetNamespace() |
| 389 | if nsName == "" { |
| 390 | return errNamespaceNotSet |
| 391 | } |
| 392 | resp, err := client.DescribeNamespace( |
| 393 | ctx, |
| 394 | &workflowservice.DescribeNamespaceRequest{Namespace: nsName}, |
| 395 | ) |
| 396 | if err != nil { |
| 397 | return serviceerror.NewUnavailablef(errUnableToGetNamespaceInfoMessage, nsName, err) |
| 398 | } |
| 399 | |
| 400 | cmCustomSearchAttributes := currentSearchAttributes.Custom() |
| 401 | upsertFieldToAliasMap := make(map[string]string) |
| 402 | fieldToAliasMap := resp.Config.CustomSearchAttributeAliases |
| 403 | aliasToFieldMap := util.InverseMap(fieldToAliasMap) |
| 404 | for saName, saType := range request.GetSearchAttributes() { |
| 405 | // check if alias is already in use |
| 406 | if _, ok := aliasToFieldMap[saName]; ok { |
| 407 | return serviceerror.NewAlreadyExistsf( |
| 408 | errSearchAttributeAlreadyExistsMessage, saName, |
| 409 | ) |
| 410 | } |
| 411 | // find the first available field for the given type |
| 412 | targetFieldName := "" |
| 413 | cntUsed := 0 |
| 414 | for fieldName, fieldType := range cmCustomSearchAttributes { |
| 415 | if fieldType != saType || !sadefs.IsPreallocatedCSAFieldName(fieldName, fieldType) { |
| 416 | continue |
| 417 | } |
| 418 | if _, ok := fieldToAliasMap[fieldName]; ok { |
| 419 | cntUsed++ |
| 420 | } else if _, ok := upsertFieldToAliasMap[fieldName]; ok { |
| 421 | cntUsed++ |
| 422 | } else { |
| 423 | targetFieldName = fieldName |
| 424 | break |
| 425 | } |
| 426 | } |
| 427 | if targetFieldName == "" { |
| 428 | return serviceerror.NewInvalidArgumentf( |
| 429 | errTooManySearchAttributesMessage, cntUsed, saType.String(), |
| 430 | ) |
| 431 | } |
| 432 | upsertFieldToAliasMap[targetFieldName] = saName |