stmtx.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2021 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 xsql
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "github.com/lf-edge/ekuiper/pkg/ast"
  19. "github.com/lf-edge/ekuiper/pkg/errorx"
  20. "github.com/lf-edge/ekuiper/pkg/kv"
  21. "strings"
  22. )
  23. func GetStreams(stmt *ast.SelectStatement) (result []string) {
  24. if stmt == nil {
  25. return nil
  26. }
  27. for _, source := range stmt.Sources {
  28. if s, ok := source.(*ast.Table); ok {
  29. result = append(result, s.Name)
  30. }
  31. }
  32. for _, join := range stmt.Joins {
  33. result = append(result, join.Name)
  34. }
  35. return
  36. }
  37. func GetStatementFromSql(sql string) (*ast.SelectStatement, error) {
  38. parser := NewParser(strings.NewReader(sql))
  39. if stmt, err := Language.Parse(parser); err != nil {
  40. return nil, fmt.Errorf("Parse SQL %s error: %s.", sql, err)
  41. } else {
  42. if r, ok := stmt.(*ast.SelectStatement); !ok {
  43. return nil, fmt.Errorf("SQL %s is not a select statement.", sql)
  44. } else {
  45. return r, nil
  46. }
  47. }
  48. }
  49. type StreamInfo struct {
  50. StreamType ast.StreamType `json:"streamType"`
  51. Statement string `json:"statement"`
  52. }
  53. func GetDataSourceStatement(m kv.KeyValue, name string) (*StreamInfo, error) {
  54. var (
  55. v string
  56. vs = &StreamInfo{}
  57. )
  58. if ok, _ := m.Get(name, &v); ok {
  59. if err := json.Unmarshal([]byte(v), vs); err != nil {
  60. return nil, fmt.Errorf("error unmarshall %s, the data in db may be corrupted", name)
  61. } else {
  62. return vs, nil
  63. }
  64. }
  65. return nil, errorx.NewWithCode(errorx.NOT_FOUND, fmt.Sprintf("%s is not found", name))
  66. }
  67. func GetDataSource(m kv.KeyValue, name string) (stmt *ast.StreamStmt, err error) {
  68. info, err := GetDataSourceStatement(m, name)
  69. if err != nil {
  70. return nil, err
  71. }
  72. parser := NewParser(strings.NewReader(info.Statement))
  73. stream, err := Language.Parse(parser)
  74. stmt, ok := stream.(*ast.StreamStmt)
  75. if !ok {
  76. err = fmt.Errorf("Error resolving the stream %s, the data in db may be corrupted.", name)
  77. }
  78. return
  79. }