converter.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. "strings"
  18. "github.com/lf-edge/ekuiper/internal/converter/binary"
  19. "github.com/lf-edge/ekuiper/internal/converter/delimited"
  20. "github.com/lf-edge/ekuiper/internal/converter/json"
  21. "github.com/lf-edge/ekuiper/pkg/ast"
  22. "github.com/lf-edge/ekuiper/pkg/message"
  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. // init once and read only
  28. var 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. func GetOrCreateConverter(options *ast.Options) (message.Converter, error) {
  40. t := strings.ToLower(options.FORMAT)
  41. if t == "" {
  42. t = message.FormatJson
  43. }
  44. if t == message.FormatJson && len(options.Schema) > 0 {
  45. return json.NewFastJsonConverter(options.Schema), nil
  46. }
  47. schemaFile := ""
  48. schemaName := options.SCHEMAID
  49. if schemaName != "" {
  50. r := strings.Split(schemaName, ".")
  51. if len(r) != 2 {
  52. return nil, fmt.Errorf("invalid schemaId: %s", schemaName)
  53. }
  54. schemaFile = r[0]
  55. schemaName = r[1]
  56. }
  57. if c, ok := converters[t]; ok {
  58. return c(schemaFile, schemaName, options.DELIMITER)
  59. }
  60. return nil, fmt.Errorf("format type %s not supported", t)
  61. }