converter.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2022-2023 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package converter
  15. import (
  16. "fmt"
  17. "github.com/lf-edge/ekuiper/internal/converter/binary"
  18. "github.com/lf-edge/ekuiper/internal/converter/delimited"
  19. "github.com/lf-edge/ekuiper/internal/converter/json"
  20. "github.com/lf-edge/ekuiper/pkg/ast"
  21. "github.com/lf-edge/ekuiper/pkg/message"
  22. "strings"
  23. )
  24. // Instantiator The format, schema information are passed in by stream options
  25. // The columns information is defined in the source side, like file source
  26. type Instantiator func(schemaFileName string, SchemaMessageName string, delimiter string) (message.Converter, error)
  27. var ( // init once and read only
  28. converters = map[string]Instantiator{
  29. message.FormatJson: func(_ string, _ string, _ string) (message.Converter, error) {
  30. return json.GetConverter()
  31. },
  32. message.FormatBinary: func(_ string, _ string, _ string) (message.Converter, error) {
  33. return binary.GetConverter()
  34. },
  35. message.FormatDelimited: func(_ string, _ string, delimiter string) (message.Converter, error) {
  36. return delimited.NewConverter(delimiter)
  37. },
  38. }
  39. )
  40. func GetOrCreateConverter(options *ast.Options) (message.Converter, error) {
  41. t := strings.ToLower(options.FORMAT)
  42. if t == "" {
  43. t = message.FormatJson
  44. }
  45. schemaFile := ""
  46. schemaName := options.SCHEMAID
  47. if schemaName != "" {
  48. r := strings.Split(schemaName, ".")
  49. if len(r) != 2 {
  50. return nil, fmt.Errorf("invalid schemaId: %s", schemaName)
  51. }
  52. schemaFile = r[0]
  53. schemaName = r[1]
  54. }
  55. if c, ok := converters[t]; ok {
  56. return c(schemaFile, schemaName, options.DELIMITER)
  57. }
  58. return nil, fmt.Errorf("format type %s not supported", t)
  59. }