github.com/kaleido-io/firefly@v0.0.0-20210622132723-8b4b6aacb971/pkg/fftypes/namearray.go (about)

     1  // Copyright © 2021 Kaleido, Inc.
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  //
     5  // Licensed under the Apache License, Version 2.0 (the "License");
     6  // you may not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //     http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing, software
    12  // distributed under the License is distributed on an "AS IS" BASIS,
    13  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  // See the License for the specific language governing permissions and
    15  // limitations under the License.
    16  
    17  package fftypes
    18  
    19  import (
    20  	"context"
    21  	"database/sql/driver"
    22  	"fmt"
    23  	"strings"
    24  
    25  	"github.com/kaleido-io/firefly/internal/i18n"
    26  )
    27  
    28  // FFNameArray is an array of strings, each conforming to the requirements
    29  // of a FireFly name, with a combined length (when joined with commas) of 1024
    30  type FFNameArray []string
    31  
    32  func (na FFNameArray) Value() (driver.Value, error) {
    33  	if na == nil {
    34  		return "", nil
    35  	}
    36  	return strings.Join([]string(na), ","), nil
    37  }
    38  
    39  func (na *FFNameArray) Scan(src interface{}) error {
    40  	switch st := src.(type) {
    41  	case string:
    42  		if st == "" {
    43  			*na = []string{}
    44  			return nil
    45  		}
    46  		*na = strings.Split(st, ",")
    47  		return nil
    48  	case []byte:
    49  		if len(st) == 0 {
    50  			*na = []string{}
    51  			return nil
    52  		}
    53  		*na = strings.Split(string(st), ",")
    54  		return nil
    55  	case FFNameArray:
    56  		*na = st
    57  		return nil
    58  	case nil:
    59  		return nil
    60  	default:
    61  		return i18n.NewError(context.Background(), i18n.MsgScanFailed, src, na)
    62  	}
    63  }
    64  
    65  func (na FFNameArray) String() string {
    66  	if na == nil {
    67  		return ""
    68  	}
    69  	return strings.Join([]string(na), ",")
    70  }
    71  
    72  func (na FFNameArray) Validate(ctx context.Context, fieldName string) error {
    73  	dupCheck := make(map[string]bool)
    74  	for i, n := range na {
    75  		if dupCheck[n] {
    76  			return i18n.NewError(ctx, i18n.MsgDuplicateArrayEntry, fieldName, i, n)
    77  		}
    78  		dupCheck[n] = true
    79  		if err := ValidateFFNameField(ctx, n, fmt.Sprintf("%s[%d]", fieldName, i)); err != nil {
    80  			return err
    81  		}
    82  	}
    83  	if len(na) > 15 {
    84  		return i18n.NewError(ctx, i18n.MsgTooManyItems, fieldName, 15, len(na))
    85  	}
    86  	return nil
    87  }