manager.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package xsql
  2. import (
  3. "fmt"
  4. "github.com/emqx/kuiper/pkg/ast"
  5. )
  6. var (
  7. Language = &ParseTree{}
  8. FuncRegisters []FunctionRegister
  9. parserFuncRuntime *funcRuntime
  10. )
  11. type ParseTree struct {
  12. Handlers map[ast.Token]func(*Parser) (ast.Statement, error)
  13. Tokens map[ast.Token]*ParseTree
  14. Keys []string
  15. }
  16. func (t *ParseTree) Handle(tok ast.Token, fn func(*Parser) (ast.Statement, error)) {
  17. // Verify that there is no conflict for this token in this parse tree.
  18. if _, conflict := t.Tokens[tok]; conflict {
  19. panic(fmt.Sprintf("conflict for token %s", tok))
  20. }
  21. if _, conflict := t.Handlers[tok]; conflict {
  22. panic(fmt.Sprintf("conflict for token %s", tok))
  23. }
  24. if t.Handlers == nil {
  25. t.Handlers = make(map[ast.Token]func(*Parser) (ast.Statement, error))
  26. }
  27. t.Handlers[tok] = fn
  28. t.Keys = append(t.Keys, tok.String())
  29. }
  30. func (pt *ParseTree) Parse(p *Parser) (ast.Statement, error) {
  31. tok, _ := p.scanIgnoreWhitespace()
  32. p.unscan()
  33. if f, ok := pt.Handlers[tok]; ok {
  34. return f(p)
  35. }
  36. return nil, nil
  37. }
  38. func init() {
  39. Language.Handle(ast.SELECT, func(p *Parser) (ast.Statement, error) {
  40. return p.Parse()
  41. })
  42. Language.Handle(ast.CREATE, func(p *Parser) (statement ast.Statement, e error) {
  43. return p.ParseCreateStmt()
  44. })
  45. Language.Handle(ast.SHOW, func(p *Parser) (statement ast.Statement, e error) {
  46. return p.parseShowStmt()
  47. })
  48. Language.Handle(ast.EXPLAIN, func(p *Parser) (statement ast.Statement, e error) {
  49. return p.parseExplainStmt()
  50. })
  51. Language.Handle(ast.DESCRIBE, func(p *Parser) (statement ast.Statement, e error) {
  52. return p.parseDescribeStmt()
  53. })
  54. Language.Handle(ast.DROP, func(p *Parser) (statement ast.Statement, e error) {
  55. return p.parseDropStmt()
  56. })
  57. InitFuncRegisters()
  58. }
  59. func InitFuncRegisters(registers ...FunctionRegister) {
  60. FuncRegisters = registers
  61. parserFuncRuntime = NewFuncRuntime(nil, registers)
  62. ast.InitFuncFinder(parserFuncRuntime)
  63. }