ast.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730
  1. package xsql
  2. import (
  3. "fmt"
  4. "github.com/emqx/kuiper/common"
  5. "github.com/emqx/kuiper/plugins"
  6. "github.com/emqx/kuiper/xstream/api"
  7. "math"
  8. "reflect"
  9. "sort"
  10. "strings"
  11. "time"
  12. )
  13. type Node interface {
  14. node()
  15. }
  16. type Expr interface {
  17. Node
  18. expr()
  19. }
  20. type Field struct {
  21. Name string
  22. AName string
  23. Expr
  24. }
  25. type Source interface {
  26. Node
  27. source()
  28. }
  29. type Sources []Source
  30. func (ss Sources) node() {}
  31. type Table struct {
  32. Name string
  33. Alias string
  34. }
  35. func (t *Table) source() {}
  36. func (ss *Table) node() {}
  37. type JoinType int
  38. const (
  39. LEFT_JOIN JoinType = iota
  40. INNER_JOIN
  41. RIGHT_JOIN
  42. FULL_JOIN
  43. CROSS_JOIN
  44. )
  45. type Join struct {
  46. Name string
  47. Alias string
  48. JoinType JoinType
  49. Expr Expr
  50. }
  51. func (j *Join) source() {}
  52. func (ss *Join) node() {}
  53. type Joins []Join
  54. func (ss Joins) node() {}
  55. type Statement interface {
  56. Stmt()
  57. Node
  58. }
  59. type SelectStatement struct {
  60. Fields Fields
  61. Sources Sources
  62. Joins Joins
  63. Condition Expr
  64. Dimensions Dimensions
  65. Having Expr
  66. SortFields SortFields
  67. }
  68. func (ss *SelectStatement) Stmt() {}
  69. func (ss *SelectStatement) node() {}
  70. type Literal interface {
  71. Expr
  72. literal()
  73. }
  74. type ParenExpr struct {
  75. Expr Expr
  76. }
  77. type ArrowExpr struct {
  78. Expr Expr
  79. }
  80. type BracketExpr struct {
  81. Expr Expr
  82. }
  83. type ColonExpr struct {
  84. Start int
  85. End int
  86. }
  87. type IndexExpr struct {
  88. Index int
  89. }
  90. type BooleanLiteral struct {
  91. Val bool
  92. }
  93. type TimeLiteral struct {
  94. Val Token
  95. }
  96. type IntegerLiteral struct {
  97. Val int
  98. }
  99. type StringLiteral struct {
  100. Val string
  101. }
  102. type NumberLiteral struct {
  103. Val float64
  104. }
  105. type Wildcard struct {
  106. Token Token
  107. }
  108. type Dimension struct {
  109. Expr Expr
  110. }
  111. type SortField struct {
  112. Name string
  113. Ascending bool
  114. }
  115. type SortFields []SortField
  116. type Dimensions []Dimension
  117. func (f *Field) expr() {}
  118. func (f *Field) node() {}
  119. func (pe *ParenExpr) expr() {}
  120. func (pe *ParenExpr) node() {}
  121. func (ae *ArrowExpr) expr() {}
  122. func (ae *ArrowExpr) node() {}
  123. func (be *BracketExpr) expr() {}
  124. func (be *BracketExpr) node() {}
  125. func (be *ColonExpr) expr() {}
  126. func (be *ColonExpr) node() {}
  127. func (be *IndexExpr) expr() {}
  128. func (be *IndexExpr) node() {}
  129. func (w *Wildcard) expr() {}
  130. func (w *Wildcard) node() {}
  131. func (bl *BooleanLiteral) expr() {}
  132. func (bl *BooleanLiteral) literal() {}
  133. func (bl *BooleanLiteral) node() {}
  134. func (tl *TimeLiteral) expr() {}
  135. func (tl *TimeLiteral) literal() {}
  136. func (tl *TimeLiteral) node() {}
  137. func (il *IntegerLiteral) expr() {}
  138. func (il *IntegerLiteral) literal() {}
  139. func (il *IntegerLiteral) node() {}
  140. func (nl *NumberLiteral) expr() {}
  141. func (nl *NumberLiteral) literal() {}
  142. func (nl *NumberLiteral) node() {}
  143. func (sl *StringLiteral) expr() {}
  144. func (sl *StringLiteral) literal() {}
  145. func (sl *StringLiteral) node() {}
  146. func (d *Dimension) expr() {}
  147. func (d *Dimension) node() {}
  148. func (d Dimensions) node() {}
  149. func (d *Dimensions) GetWindow() *Window {
  150. for _, child := range *d {
  151. if w, ok := child.Expr.(*Window); ok {
  152. return w
  153. }
  154. }
  155. return nil
  156. }
  157. func (d *Dimensions) GetGroups() Dimensions {
  158. var nd Dimensions
  159. for _, child := range *d {
  160. if _, ok := child.Expr.(*Window); !ok {
  161. nd = append(nd, child)
  162. }
  163. }
  164. return nd
  165. }
  166. func (sf *SortField) expr() {}
  167. func (sf *SortField) node() {}
  168. func (sf SortFields) node() {}
  169. type Call struct {
  170. Name string
  171. Args []Expr
  172. }
  173. func (c *Call) expr() {}
  174. func (c *Call) literal() {}
  175. func (c *Call) node() {}
  176. type WindowType int
  177. const (
  178. NOT_WINDOW WindowType = iota
  179. TUMBLING_WINDOW
  180. HOPPING_WINDOW
  181. SLIDING_WINDOW
  182. SESSION_WINDOW
  183. )
  184. type Window struct {
  185. WindowType WindowType
  186. Length *IntegerLiteral
  187. Interval *IntegerLiteral
  188. }
  189. func (w *Window) expr() {}
  190. func (w *Window) literal() {}
  191. func (w *Window) node() {}
  192. type SelectStatements []SelectStatement
  193. func (ss *SelectStatements) node() {}
  194. type Fields []Field
  195. func (fs Fields) node() {}
  196. type BinaryExpr struct {
  197. OP Token
  198. LHS Expr
  199. RHS Expr
  200. }
  201. func (fe *BinaryExpr) expr() {}
  202. func (be *BinaryExpr) node() {}
  203. type FieldRef struct {
  204. StreamName StreamName
  205. Name string
  206. }
  207. func (fr *FieldRef) expr() {}
  208. func (fr *FieldRef) node() {}
  209. type MetaRef struct {
  210. StreamName StreamName
  211. Name string
  212. }
  213. func (fr *MetaRef) expr() {}
  214. func (fr *MetaRef) node() {}
  215. // The stream AST tree
  216. type Options map[string]string
  217. func (o Options) node() {}
  218. type StreamName string
  219. func (sn *StreamName) node() {}
  220. type StreamStmt struct {
  221. Name StreamName
  222. StreamFields StreamFields
  223. Options Options
  224. }
  225. func (ss *StreamStmt) node() {}
  226. func (ss *StreamStmt) Stmt() {}
  227. func (ss *StreamStmt) isSchemaless() bool {
  228. return ss.StreamFields == nil
  229. }
  230. type FieldType interface {
  231. fieldType()
  232. Node
  233. }
  234. type StreamField struct {
  235. Name string
  236. FieldType
  237. }
  238. type StreamFields []StreamField
  239. func (sf StreamFields) node() {}
  240. type BasicType struct {
  241. Type DataType
  242. }
  243. func (bt *BasicType) fieldType() {}
  244. func (bt *BasicType) node() {}
  245. type ArrayType struct {
  246. Type DataType
  247. FieldType
  248. }
  249. func (at *ArrayType) fieldType() {}
  250. func (at *ArrayType) node() {}
  251. type RecType struct {
  252. StreamFields StreamFields
  253. }
  254. func (rt *RecType) fieldType() {}
  255. func (rt *RecType) node() {}
  256. type ShowStreamsStatement struct {
  257. }
  258. type DescribeStreamStatement struct {
  259. Name string
  260. }
  261. type ExplainStreamStatement struct {
  262. Name string
  263. }
  264. type DropStreamStatement struct {
  265. Name string
  266. }
  267. func (ss *ShowStreamsStatement) Stmt() {}
  268. func (ss *ShowStreamsStatement) node() {}
  269. func (dss *DescribeStreamStatement) Stmt() {}
  270. func (dss *DescribeStreamStatement) node() {}
  271. func (ess *ExplainStreamStatement) Stmt() {}
  272. func (ess *ExplainStreamStatement) node() {}
  273. func (dss *DropStreamStatement) Stmt() {}
  274. func (dss *DropStreamStatement) node() {}
  275. type Visitor interface {
  276. Visit(Node) Visitor
  277. }
  278. func Walk(v Visitor, node Node) {
  279. if node == nil {
  280. return
  281. }
  282. if v = v.Visit(node); v == nil {
  283. return
  284. }
  285. switch n := node.(type) {
  286. case *BinaryExpr:
  287. Walk(v, n.LHS)
  288. Walk(v, n.RHS)
  289. case *Call:
  290. for _, expr := range n.Args {
  291. Walk(v, expr)
  292. }
  293. case *Window:
  294. Walk(v, n.Length)
  295. Walk(v, n.Interval)
  296. case *Field:
  297. Walk(v, n.Expr)
  298. case Fields:
  299. for _, c := range n {
  300. Walk(v, &c)
  301. }
  302. case *ParenExpr:
  303. Walk(v, n.Expr)
  304. case *SelectStatement:
  305. Walk(v, n.Fields)
  306. Walk(v, n.Dimensions)
  307. Walk(v, n.Sources)
  308. Walk(v, n.Joins)
  309. Walk(v, n.Condition)
  310. Walk(v, n.SortFields)
  311. case SortFields:
  312. for _, sf := range n {
  313. Walk(v, &sf)
  314. }
  315. case Sources:
  316. for _, s := range n {
  317. Walk(v, s)
  318. }
  319. case Joins:
  320. for _, s := range n {
  321. Walk(v, &s)
  322. }
  323. case *Join:
  324. Walk(v, n.Expr)
  325. case *StreamStmt:
  326. Walk(v, &n.Name)
  327. Walk(v, n.StreamFields)
  328. Walk(v, n.Options)
  329. case *BasicType:
  330. Walk(v, n)
  331. case *ArrayType:
  332. Walk(v, n)
  333. case *RecType:
  334. Walk(v, n)
  335. case *ShowStreamsStatement:
  336. Walk(v, n)
  337. case *DescribeStreamStatement:
  338. Walk(v, n)
  339. case *ExplainStreamStatement:
  340. Walk(v, n)
  341. case *DropStreamStatement:
  342. Walk(v, n)
  343. }
  344. }
  345. // WalkFunc traverses a node hierarchy in depth-first order.
  346. func WalkFunc(node Node, fn func(Node)) {
  347. Walk(walkFuncVisitor(fn), node)
  348. }
  349. type walkFuncVisitor func(Node)
  350. func (fn walkFuncVisitor) Visit(n Node) Visitor { fn(n); return fn }
  351. // Valuer is the interface that wraps the Value() method.
  352. type Valuer interface {
  353. // Value returns the value and existence flag for a given key.
  354. Value(key string) (interface{}, bool)
  355. Meta(key string) (interface{}, bool)
  356. }
  357. // CallValuer implements the Call method for evaluating function calls.
  358. type CallValuer interface {
  359. Valuer
  360. // Call is invoked to evaluate a function call (if possible).
  361. Call(name string, args []interface{}) (interface{}, bool)
  362. }
  363. type AggregateCallValuer interface {
  364. CallValuer
  365. GetAllTuples() AggregateData
  366. }
  367. type Wildcarder interface {
  368. // Value returns the value and existence flag for a given key.
  369. All(stream string) (interface{}, bool)
  370. }
  371. type DataValuer interface {
  372. Valuer
  373. Wildcarder
  374. }
  375. type WildcardValuer struct {
  376. Data Wildcarder
  377. }
  378. //TODO deal with wildcard of a stream, e.g. SELECT Table.* from Table inner join Table1
  379. func (wv *WildcardValuer) Value(key string) (interface{}, bool) {
  380. if key == "" {
  381. return wv.Data.All(key)
  382. } else {
  383. a := strings.Index(key, ".*")
  384. if a <= 0 {
  385. return nil, false
  386. } else {
  387. return wv.Data.All(key[:a])
  388. }
  389. }
  390. }
  391. func (wv *WildcardValuer) Meta(key string) (interface{}, bool) {
  392. return nil, false
  393. }
  394. /**********************************
  395. ** Various Data Types for SQL transformation
  396. */
  397. type AggregateData interface {
  398. AggregateEval(expr Expr) []interface{}
  399. }
  400. // Message is a valuer that substitutes values for the mapped interface.
  401. type Message map[string]interface{}
  402. // Value returns the value for a key in the Message.
  403. func (m Message) Value(key string) (interface{}, bool) {
  404. key = strings.ToLower(key)
  405. if keys := strings.Split(key, "."); len(keys) == 1 {
  406. v, ok := m[key]
  407. return v, ok
  408. } else if len(keys) == 2 {
  409. v, ok := m[keys[1]]
  410. return v, ok
  411. }
  412. common.Log.Println("Invalid key: " + key + ", expect source.field or field.")
  413. return nil, false
  414. }
  415. func (m Message) Meta(key string) (interface{}, bool) {
  416. if key == "*" {
  417. return map[string]interface{}(m), true
  418. }
  419. return m.Value(key)
  420. }
  421. type Event interface {
  422. GetTimestamp() int64
  423. IsWatermark() bool
  424. }
  425. type Metadata Message
  426. func (m Metadata) Value(key string) (interface{}, bool) {
  427. msg := Message(m)
  428. return msg.Value(key)
  429. }
  430. func (m Metadata) Meta(key string) (interface{}, bool) {
  431. if key == "*" {
  432. return map[string]interface{}(m), true
  433. }
  434. msg := Message(m)
  435. return msg.Meta(key)
  436. }
  437. type Tuple struct {
  438. Emitter string
  439. Message Message
  440. Timestamp int64
  441. Metadata Metadata
  442. }
  443. func (t *Tuple) Value(key string) (interface{}, bool) {
  444. return t.Message.Value(key)
  445. }
  446. func (t *Tuple) Meta(key string) (interface{}, bool) {
  447. if key == "*" {
  448. return map[string]interface{}(t.Metadata), true
  449. }
  450. return t.Metadata.Value(key)
  451. }
  452. func (t *Tuple) All(stream string) (interface{}, bool) {
  453. return t.Message, true
  454. }
  455. func (t *Tuple) AggregateEval(expr Expr) []interface{} {
  456. return []interface{}{Eval(expr, t)}
  457. }
  458. func (t *Tuple) GetTimestamp() int64 {
  459. return t.Timestamp
  460. }
  461. func (t *Tuple) GetMetadata() Metadata {
  462. return t.Metadata
  463. }
  464. func (t *Tuple) IsWatermark() bool {
  465. return false
  466. }
  467. type WindowTuples struct {
  468. Emitter string
  469. Tuples []Tuple
  470. }
  471. type WindowTuplesSet []WindowTuples
  472. func (w WindowTuplesSet) GetBySrc(src string) []Tuple {
  473. for _, me := range w {
  474. if me.Emitter == src {
  475. return me.Tuples
  476. }
  477. }
  478. return nil
  479. }
  480. func (w WindowTuplesSet) Len() int {
  481. if len(w) > 0 {
  482. return len(w[0].Tuples)
  483. }
  484. return 0
  485. }
  486. func (w WindowTuplesSet) Swap(i, j int) {
  487. if len(w) > 0 {
  488. s := w[0].Tuples
  489. s[i], s[j] = s[j], s[i]
  490. }
  491. }
  492. func (w WindowTuplesSet) Index(i int) Valuer {
  493. if len(w) > 0 {
  494. s := w[0].Tuples
  495. return &(s[i])
  496. }
  497. return nil
  498. }
  499. func (w WindowTuplesSet) AddTuple(tuple *Tuple) WindowTuplesSet {
  500. found := false
  501. for i, t := range w {
  502. if t.Emitter == tuple.Emitter {
  503. t.Tuples = append(t.Tuples, *tuple)
  504. found = true
  505. w[i] = t
  506. break
  507. }
  508. }
  509. if !found {
  510. ets := &WindowTuples{Emitter: tuple.Emitter}
  511. ets.Tuples = append(ets.Tuples, *tuple)
  512. w = append(w, *ets)
  513. }
  514. return w
  515. }
  516. //Sort by tuple timestamp
  517. func (w WindowTuplesSet) Sort() {
  518. for _, t := range w {
  519. tuples := t.Tuples
  520. sort.SliceStable(tuples, func(i, j int) bool {
  521. return tuples[i].Timestamp < tuples[j].Timestamp
  522. })
  523. t.Tuples = tuples
  524. }
  525. }
  526. func (w WindowTuplesSet) AggregateEval(expr Expr) []interface{} {
  527. var result []interface{}
  528. if len(w) != 1 { //should never happen
  529. return nil
  530. }
  531. for _, t := range w[0].Tuples {
  532. result = append(result, Eval(expr, &t))
  533. }
  534. return result
  535. }
  536. type JoinTuple struct {
  537. Tuples []Tuple
  538. }
  539. func (jt *JoinTuple) AddTuple(tuple Tuple) {
  540. jt.Tuples = append(jt.Tuples, tuple)
  541. }
  542. func (jt *JoinTuple) AddTuples(tuples []Tuple) {
  543. for _, t := range tuples {
  544. jt.Tuples = append(jt.Tuples, t)
  545. }
  546. }
  547. func getTupleValue(tuple Tuple, t string, key string) (interface{}, bool) {
  548. switch t {
  549. case "value":
  550. return tuple.Value(key)
  551. case "meta":
  552. return tuple.Meta(key)
  553. default:
  554. common.Log.Errorf("cannot get tuple for type %s", t)
  555. return nil, false
  556. }
  557. }
  558. func (jt *JoinTuple) doGetValue(t string, key string) (interface{}, bool) {
  559. keys := strings.Split(key, ".")
  560. tuples := jt.Tuples
  561. switch len(keys) {
  562. case 1:
  563. if len(tuples) > 1 {
  564. for _, tuple := range tuples { //TODO support key without modifier?
  565. v, ok := getTupleValue(tuple, t, key)
  566. if ok {
  567. return v, ok
  568. }
  569. }
  570. common.Log.Infoln("Wrong key: ", key, ", not found")
  571. return nil, false
  572. } else {
  573. return getTupleValue(tuples[0], t, key)
  574. }
  575. case 2:
  576. emitter, key := keys[0], keys[1]
  577. //TODO should use hash here
  578. for _, tuple := range tuples {
  579. if tuple.Emitter == emitter {
  580. return getTupleValue(tuple, t, key)
  581. }
  582. }
  583. return nil, false
  584. default:
  585. common.Log.Infoln("Wrong key: ", key, ", expect dot in the expression.")
  586. return nil, false
  587. }
  588. }
  589. func (jt *JoinTuple) Value(key string) (interface{}, bool) {
  590. return jt.doGetValue("value", key)
  591. }
  592. func (jt *JoinTuple) Meta(key string) (interface{}, bool) {
  593. return jt.doGetValue("meta", key)
  594. }
  595. func (jt *JoinTuple) All(stream string) (interface{}, bool) {
  596. if stream != "" {
  597. for _, t := range jt.Tuples {
  598. if t.Emitter == stream {
  599. return t.Message, true
  600. }
  601. }
  602. } else {
  603. var r Message = make(map[string]interface{})
  604. for _, t := range jt.Tuples {
  605. for k, v := range t.Message {
  606. if _, ok := r[k]; !ok {
  607. r[k] = v
  608. }
  609. }
  610. }
  611. return r, true
  612. }
  613. return nil, false
  614. }
  615. type JoinTupleSets []JoinTuple
  616. func (s JoinTupleSets) Len() int { return len(s) }
  617. func (s JoinTupleSets) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  618. func (s JoinTupleSets) Index(i int) Valuer { return &(s[i]) }
  619. func (s JoinTupleSets) AggregateEval(expr Expr) []interface{} {
  620. var result []interface{}
  621. for _, t := range s {
  622. result = append(result, Eval(expr, &t))
  623. }
  624. return result
  625. }
  626. type GroupedTuples []DataValuer
  627. func (s GroupedTuples) AggregateEval(expr Expr) []interface{} {
  628. var result []interface{}
  629. for _, t := range s {
  630. result = append(result, Eval(expr, t))
  631. }
  632. return result
  633. }
  634. type GroupedTuplesSet []GroupedTuples
  635. func (s GroupedTuplesSet) Len() int { return len(s) }
  636. func (s GroupedTuplesSet) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  637. func (s GroupedTuplesSet) Index(i int) Valuer { return s[i][0] }
  638. type SortingData interface {
  639. Len() int
  640. Swap(i, j int)
  641. Index(i int) Valuer
  642. }
  643. // multiSorter implements the Sort interface, sorting the changes within.Hi
  644. type MultiSorter struct {
  645. SortingData
  646. fields SortFields
  647. values []map[string]interface{}
  648. }
  649. // OrderedBy returns a Sorter that sorts using the less functions, in order.
  650. // Call its Sort method to sort the data.
  651. func OrderedBy(fields SortFields) *MultiSorter {
  652. return &MultiSorter{
  653. fields: fields,
  654. }
  655. }
  656. // Less is part of sort.Interface. It is implemented by looping along the
  657. // less functions until it finds a comparison that discriminates between
  658. // the two items (one is less than the other). Note that it can call the
  659. // less functions twice per call. We could change the functions to return
  660. // -1, 0, 1 and reduce the number of calls for greater efficiency: an
  661. // exercise for the reader.
  662. func (ms *MultiSorter) Less(i, j int) bool {
  663. p, q := ms.values[i], ms.values[j]
  664. v := &ValuerEval{Valuer: MultiValuer(&FunctionValuer{})}
  665. for _, field := range ms.fields {
  666. n := field.Name
  667. vp, _ := p[n]
  668. vq, _ := q[n]
  669. if vp == nil && vq != nil {
  670. return false
  671. } else if vp != nil && vq == nil {
  672. ms.valueSwap(true, i, j)
  673. return true
  674. } else if vp == nil && vq == nil {
  675. return false
  676. }
  677. switch {
  678. case v.simpleDataEval(vp, vq, LT):
  679. ms.valueSwap(field.Ascending, i, j)
  680. return field.Ascending
  681. case v.simpleDataEval(vq, vp, LT):
  682. ms.valueSwap(!field.Ascending, i, j)
  683. return !field.Ascending
  684. }
  685. }
  686. return false
  687. }
  688. func (ms *MultiSorter) valueSwap(s bool, i, j int) {
  689. if s {
  690. ms.values[i], ms.values[j] = ms.values[j], ms.values[i]
  691. }
  692. }
  693. // Sort sorts the argument slice according to the less functions passed to OrderedBy.
  694. func (ms *MultiSorter) Sort(data SortingData) error {
  695. ms.SortingData = data
  696. types := make([]string, len(ms.fields))
  697. ms.values = make([]map[string]interface{}, data.Len())
  698. //load and validate data
  699. for i := 0; i < data.Len(); i++ {
  700. ms.values[i] = make(map[string]interface{})
  701. p := data.Index(i)
  702. vep := &ValuerEval{Valuer: MultiValuer(p, &FunctionValuer{})}
  703. for j, field := range ms.fields {
  704. n := field.Name
  705. vp, _ := vep.Valuer.Value(n)
  706. if err, ok := vp.(error); ok {
  707. return err
  708. } else {
  709. if types[j] == "" && vp != nil {
  710. types[j] = fmt.Sprintf("%T", vp)
  711. }
  712. if err := validate(types[j], vp); err != nil {
  713. return err
  714. } else {
  715. ms.values[i][n] = vp
  716. }
  717. }
  718. }
  719. }
  720. sort.Sort(ms)
  721. return nil
  722. }
  723. func validate(t string, v interface{}) error {
  724. if v == nil || t == "" {
  725. return nil
  726. }
  727. vt := fmt.Sprintf("%T", v)
  728. switch t {
  729. case "int", "int64", "float64", "uint64":
  730. if vt == "int" || vt == "int64" || vt == "float64" || vt == "uint64" {
  731. return nil
  732. } else {
  733. return fmt.Errorf("incompatible types for comparison: %s and %s", t, vt)
  734. }
  735. case "bool":
  736. if vt == "bool" {
  737. return nil
  738. } else {
  739. return fmt.Errorf("incompatible types for comparison: %s and %s", t, vt)
  740. }
  741. case "string":
  742. if vt == "string" {
  743. return nil
  744. } else {
  745. return fmt.Errorf("incompatible types for comparison: %s and %s", t, vt)
  746. }
  747. case "time.Time":
  748. _, err := common.InterfaceToTime(v, "")
  749. if err != nil {
  750. return fmt.Errorf("incompatible types for comparison: %s and %s", t, vt)
  751. } else {
  752. return nil
  753. }
  754. default:
  755. return fmt.Errorf("incompatible types for comparison: %s and %s", t, vt)
  756. }
  757. return nil
  758. }
  759. type EvalResultMessage struct {
  760. Emitter string
  761. Result interface{}
  762. Message Message
  763. }
  764. type ResultsAndMessages []EvalResultMessage
  765. // Eval evaluates expr against a map.
  766. func Eval(expr Expr, m Valuer) interface{} {
  767. eval := ValuerEval{Valuer: MultiValuer(m, &FunctionValuer{})}
  768. return eval.Eval(expr)
  769. }
  770. // ValuerEval will evaluate an expression using the Valuer.
  771. type ValuerEval struct {
  772. Valuer Valuer
  773. // IntegerFloatDivision will set the eval system to treat
  774. // a division between two integers as a floating point division.
  775. IntegerFloatDivision bool
  776. }
  777. // MultiValuer returns a Valuer that iterates over multiple Valuer instances
  778. // to find a match.
  779. func MultiValuer(valuers ...Valuer) Valuer {
  780. return multiValuer(valuers)
  781. }
  782. type multiValuer []Valuer
  783. func (a multiValuer) Value(key string) (interface{}, bool) {
  784. for _, valuer := range a {
  785. if v, ok := valuer.Value(key); ok {
  786. return v, true
  787. }
  788. }
  789. return nil, false
  790. }
  791. func (a multiValuer) Meta(key string) (interface{}, bool) {
  792. for _, valuer := range a {
  793. if v, ok := valuer.Meta(key); ok {
  794. return v, true
  795. }
  796. }
  797. return nil, false
  798. }
  799. func (a multiValuer) Call(name string, args []interface{}) (interface{}, bool) {
  800. for _, valuer := range a {
  801. if valuer, ok := valuer.(CallValuer); ok {
  802. if v, ok := valuer.Call(name, args); ok {
  803. return v, true
  804. } else {
  805. return fmt.Errorf("call func %s error: %v", name, v), false
  806. }
  807. }
  808. }
  809. return nil, false
  810. }
  811. type multiAggregateValuer struct {
  812. data AggregateData
  813. multiValuer
  814. }
  815. func MultiAggregateValuer(data AggregateData, valuers ...Valuer) Valuer {
  816. return &multiAggregateValuer{
  817. data: data,
  818. multiValuer: valuers,
  819. }
  820. }
  821. //The args is [][] for aggregation
  822. func (a *multiAggregateValuer) Call(name string, args []interface{}) (interface{}, bool) {
  823. var singleArgs []interface{} = nil
  824. for _, valuer := range a.multiValuer {
  825. if a, ok := valuer.(AggregateCallValuer); ok {
  826. if v, ok := a.Call(name, args); ok {
  827. return v, true
  828. } else {
  829. return fmt.Errorf("call func %s error: %v", name, v), false
  830. }
  831. } else if c, ok := valuer.(CallValuer); ok {
  832. if singleArgs == nil {
  833. for _, arg := range args {
  834. if arg, ok := arg.([]interface{}); ok {
  835. singleArgs = append(singleArgs, arg[0])
  836. } else {
  837. common.Log.Infof("multiAggregateValuer does not get [][] args but get %v", args)
  838. return nil, false
  839. }
  840. }
  841. }
  842. if v, ok := c.Call(name, singleArgs); ok {
  843. return v, true
  844. }
  845. }
  846. }
  847. return nil, false
  848. }
  849. func (a *multiAggregateValuer) GetAllTuples() AggregateData {
  850. return a.data
  851. }
  852. type BracketEvalResult struct {
  853. Start, End int
  854. }
  855. func (ber *BracketEvalResult) isIndex() bool {
  856. return ber.Start == ber.End
  857. }
  858. // Eval evaluates an expression and returns a value.
  859. func (v *ValuerEval) Eval(expr Expr) interface{} {
  860. if expr == nil {
  861. return nil
  862. }
  863. switch expr := expr.(type) {
  864. case *BinaryExpr:
  865. return v.evalBinaryExpr(expr)
  866. //case *BooleanLiteral:
  867. // return expr.Val
  868. case *IntegerLiteral:
  869. return expr.Val
  870. case *NumberLiteral:
  871. return expr.Val
  872. case *ParenExpr:
  873. return v.Eval(expr.Expr)
  874. case *StringLiteral:
  875. return expr.Val
  876. case *BooleanLiteral:
  877. return expr.Val
  878. case *ColonExpr:
  879. return &BracketEvalResult{Start: expr.Start, End: expr.End}
  880. case *IndexExpr:
  881. return &BracketEvalResult{Start: expr.Index, End: expr.Index}
  882. case *Call:
  883. if valuer, ok := v.Valuer.(CallValuer); ok {
  884. var args []interface{}
  885. if len(expr.Args) > 0 {
  886. args = make([]interface{}, len(expr.Args))
  887. if aggreValuer, ok := valuer.(AggregateCallValuer); ok {
  888. for i := range expr.Args {
  889. args[i] = aggreValuer.GetAllTuples().AggregateEval(expr.Args[i])
  890. }
  891. } else {
  892. for i := range expr.Args {
  893. args[i] = v.Eval(expr.Args[i])
  894. if _, ok := args[i].(error); ok {
  895. return args[i]
  896. }
  897. }
  898. }
  899. }
  900. val, _ := valuer.Call(expr.Name, args)
  901. return val
  902. }
  903. return nil
  904. case *FieldRef:
  905. if expr.StreamName == "" {
  906. val, _ := v.Valuer.Value(expr.Name)
  907. return val
  908. } else {
  909. //The field specified with stream source
  910. val, _ := v.Valuer.Value(string(expr.StreamName) + "." + expr.Name)
  911. return val
  912. }
  913. case *MetaRef:
  914. if expr.StreamName == "" {
  915. val, _ := v.Valuer.Meta(expr.Name)
  916. return val
  917. } else {
  918. //The field specified with stream source
  919. val, _ := v.Valuer.Meta(string(expr.StreamName) + "." + expr.Name)
  920. return val
  921. }
  922. case *Wildcard:
  923. val, _ := v.Valuer.Value("")
  924. return val
  925. default:
  926. return nil
  927. }
  928. }
  929. func (v *ValuerEval) evalBinaryExpr(expr *BinaryExpr) interface{} {
  930. lhs := v.Eval(expr.LHS)
  931. switch val := lhs.(type) {
  932. case map[string]interface{}:
  933. return v.evalJsonExpr(val, expr.OP, expr.RHS)
  934. case []interface{}, []map[string]interface{}:
  935. return v.evalJsonExpr(val, expr.OP, expr.RHS)
  936. case error:
  937. return val
  938. }
  939. rhs := v.Eval(expr.RHS)
  940. if _, ok := rhs.(error); ok {
  941. return rhs
  942. }
  943. return v.simpleDataEval(lhs, rhs, expr.OP)
  944. }
  945. func (v *ValuerEval) evalJsonExpr(result interface{}, op Token, expr Expr) interface{} {
  946. switch val := result.(type) {
  947. case map[string]interface{}:
  948. switch op {
  949. case ARROW:
  950. switch e := expr.(type) {
  951. case *FieldRef, *MetaRef:
  952. ve := &ValuerEval{Valuer: Message(val)}
  953. return ve.Eval(e)
  954. default:
  955. return fmt.Errorf("the right expression is not a field reference node")
  956. }
  957. default:
  958. return fmt.Errorf("%v is an invalid operation for %T", op, val)
  959. }
  960. case []interface{}, []map[string]interface{}:
  961. switch op {
  962. case SUBSET:
  963. val := reflect.ValueOf(result)
  964. ber := v.Eval(expr)
  965. if berVal, ok1 := ber.(*BracketEvalResult); ok1 {
  966. if berVal.isIndex() {
  967. if berVal.Start >= val.Len() {
  968. return fmt.Errorf("out of index: %d of %d", berVal.Start, val.Len())
  969. }
  970. return val.Index(berVal.Start).Interface()
  971. } else {
  972. if berVal.Start >= val.Len() {
  973. return fmt.Errorf("start value is out of index: %d of %d", berVal.Start, val.Len())
  974. }
  975. if berVal.End >= val.Len() {
  976. return fmt.Errorf("end value is out of index: %d of %d", berVal.End, val.Len())
  977. }
  978. return val.Slice(berVal.Start, berVal.End).Interface()
  979. }
  980. } else {
  981. return fmt.Errorf("invalid evaluation result - %v", berVal)
  982. }
  983. default:
  984. return fmt.Errorf("%v is an invalid operation for %T", op, val)
  985. }
  986. }
  987. return nil
  988. }
  989. //lhs and rhs are non-nil
  990. func (v *ValuerEval) simpleDataEval(lhs, rhs interface{}, op Token) interface{} {
  991. if lhs == nil || rhs == nil {
  992. switch op {
  993. case EQ, LTE, GTE:
  994. if lhs == nil && rhs == nil {
  995. return true
  996. } else {
  997. return false
  998. }
  999. case NEQ:
  1000. if lhs == nil && rhs == nil {
  1001. return false
  1002. } else {
  1003. return true
  1004. }
  1005. case LT, GT:
  1006. return false
  1007. default:
  1008. return nil
  1009. }
  1010. }
  1011. lhs = convertNum(lhs)
  1012. rhs = convertNum(rhs)
  1013. // Evaluate if both sides are simple types.
  1014. switch lhs := lhs.(type) {
  1015. case bool:
  1016. rhs, ok := rhs.(bool)
  1017. if !ok {
  1018. return invalidOpError(lhs, op, rhs)
  1019. }
  1020. switch op {
  1021. case AND:
  1022. return lhs && rhs
  1023. case OR:
  1024. return lhs || rhs
  1025. case BITWISE_AND:
  1026. return lhs && rhs
  1027. case BITWISE_OR:
  1028. return lhs || rhs
  1029. case BITWISE_XOR:
  1030. return lhs != rhs
  1031. case EQ:
  1032. return lhs == rhs
  1033. case NEQ:
  1034. return lhs != rhs
  1035. default:
  1036. return invalidOpError(lhs, op, rhs)
  1037. }
  1038. case float64:
  1039. // Try the rhs as a float64, int64, or uint64
  1040. rhsf, ok := rhs.(float64)
  1041. if !ok {
  1042. switch val := rhs.(type) {
  1043. case int64:
  1044. rhsf, ok = float64(val), true
  1045. case uint64:
  1046. rhsf, ok = float64(val), true
  1047. }
  1048. }
  1049. if !ok {
  1050. return invalidOpError(lhs, op, rhs)
  1051. }
  1052. rhs := rhsf
  1053. switch op {
  1054. case EQ:
  1055. return lhs == rhs
  1056. case NEQ:
  1057. return lhs != rhs
  1058. case LT:
  1059. return lhs < rhs
  1060. case LTE:
  1061. return lhs <= rhs
  1062. case GT:
  1063. return lhs > rhs
  1064. case GTE:
  1065. return lhs >= rhs
  1066. case ADD:
  1067. return lhs + rhs
  1068. case SUB:
  1069. return lhs - rhs
  1070. case MUL:
  1071. return lhs * rhs
  1072. case DIV:
  1073. if rhs == 0 {
  1074. return fmt.Errorf("divided by zero")
  1075. }
  1076. return lhs / rhs
  1077. case MOD:
  1078. if rhs == 0 {
  1079. return fmt.Errorf("divided by zero")
  1080. }
  1081. return math.Mod(lhs, rhs)
  1082. default:
  1083. return invalidOpError(lhs, op, rhs)
  1084. }
  1085. case int64:
  1086. // Try as a float64 to see if a float cast is required.
  1087. switch rhs := rhs.(type) {
  1088. case float64:
  1089. lhs := float64(lhs)
  1090. switch op {
  1091. case EQ:
  1092. return lhs == rhs
  1093. case NEQ:
  1094. return lhs != rhs
  1095. case LT:
  1096. return lhs < rhs
  1097. case LTE:
  1098. return lhs <= rhs
  1099. case GT:
  1100. return lhs > rhs
  1101. case GTE:
  1102. return lhs >= rhs
  1103. case ADD:
  1104. return lhs + rhs
  1105. case SUB:
  1106. return lhs - rhs
  1107. case MUL:
  1108. return lhs * rhs
  1109. case DIV:
  1110. if rhs == 0 {
  1111. return fmt.Errorf("divided by zero")
  1112. }
  1113. return lhs / rhs
  1114. case MOD:
  1115. if rhs == 0 {
  1116. return fmt.Errorf("divided by zero")
  1117. }
  1118. return math.Mod(lhs, rhs)
  1119. default:
  1120. return invalidOpError(lhs, op, rhs)
  1121. }
  1122. case int64:
  1123. switch op {
  1124. case EQ:
  1125. return lhs == rhs
  1126. case NEQ:
  1127. return lhs != rhs
  1128. case LT:
  1129. return lhs < rhs
  1130. case LTE:
  1131. return lhs <= rhs
  1132. case GT:
  1133. return lhs > rhs
  1134. case GTE:
  1135. return lhs >= rhs
  1136. case ADD:
  1137. return lhs + rhs
  1138. case SUB:
  1139. return lhs - rhs
  1140. case MUL:
  1141. return lhs * rhs
  1142. case DIV:
  1143. if v.IntegerFloatDivision {
  1144. if rhs == 0 {
  1145. return fmt.Errorf("divided by zero")
  1146. }
  1147. return float64(lhs) / float64(rhs)
  1148. }
  1149. if rhs == 0 {
  1150. return fmt.Errorf("divided by zero")
  1151. }
  1152. return lhs / rhs
  1153. case MOD:
  1154. if rhs == 0 {
  1155. return fmt.Errorf("divided by zero")
  1156. }
  1157. return lhs % rhs
  1158. case BITWISE_AND:
  1159. return lhs & rhs
  1160. case BITWISE_OR:
  1161. return lhs | rhs
  1162. case BITWISE_XOR:
  1163. return lhs ^ rhs
  1164. default:
  1165. return invalidOpError(lhs, op, rhs)
  1166. }
  1167. case uint64:
  1168. switch op {
  1169. case EQ:
  1170. return uint64(lhs) == rhs
  1171. case NEQ:
  1172. return uint64(lhs) != rhs
  1173. case LT:
  1174. if lhs < 0 {
  1175. return true
  1176. }
  1177. return uint64(lhs) < rhs
  1178. case LTE:
  1179. if lhs < 0 {
  1180. return true
  1181. }
  1182. return uint64(lhs) <= rhs
  1183. case GT:
  1184. if lhs < 0 {
  1185. return false
  1186. }
  1187. return uint64(lhs) > rhs
  1188. case GTE:
  1189. if lhs < 0 {
  1190. return false
  1191. }
  1192. return uint64(lhs) >= rhs
  1193. case ADD:
  1194. return uint64(lhs) + rhs
  1195. case SUB:
  1196. return uint64(lhs) - rhs
  1197. case MUL:
  1198. return uint64(lhs) * rhs
  1199. case DIV:
  1200. if rhs == 0 {
  1201. return fmt.Errorf("divided by zero")
  1202. }
  1203. return uint64(lhs) / rhs
  1204. case MOD:
  1205. if rhs == 0 {
  1206. return fmt.Errorf("divided by zero")
  1207. }
  1208. return uint64(lhs) % rhs
  1209. case BITWISE_AND:
  1210. return uint64(lhs) & rhs
  1211. case BITWISE_OR:
  1212. return uint64(lhs) | rhs
  1213. case BITWISE_XOR:
  1214. return uint64(lhs) ^ rhs
  1215. default:
  1216. return invalidOpError(lhs, op, rhs)
  1217. }
  1218. default:
  1219. return invalidOpError(lhs, op, rhs)
  1220. }
  1221. case uint64:
  1222. // Try as a float64 to see if a float cast is required.
  1223. switch rhs := rhs.(type) {
  1224. case float64:
  1225. lhs := float64(lhs)
  1226. switch op {
  1227. case EQ:
  1228. return lhs == rhs
  1229. case NEQ:
  1230. return lhs != rhs
  1231. case LT:
  1232. return lhs < rhs
  1233. case LTE:
  1234. return lhs <= rhs
  1235. case GT:
  1236. return lhs > rhs
  1237. case GTE:
  1238. return lhs >= rhs
  1239. case ADD:
  1240. return lhs + rhs
  1241. case SUB:
  1242. return lhs - rhs
  1243. case MUL:
  1244. return lhs * rhs
  1245. case DIV:
  1246. if rhs == 0 {
  1247. return fmt.Errorf("divided by zero")
  1248. }
  1249. return lhs / rhs
  1250. case MOD:
  1251. if rhs == 0 {
  1252. return fmt.Errorf("divided by zero")
  1253. }
  1254. return math.Mod(lhs, rhs)
  1255. default:
  1256. return invalidOpError(lhs, op, rhs)
  1257. }
  1258. case int64:
  1259. switch op {
  1260. case EQ:
  1261. return lhs == uint64(rhs)
  1262. case NEQ:
  1263. return lhs != uint64(rhs)
  1264. case LT:
  1265. if rhs < 0 {
  1266. return false
  1267. }
  1268. return lhs < uint64(rhs)
  1269. case LTE:
  1270. if rhs < 0 {
  1271. return false
  1272. }
  1273. return lhs <= uint64(rhs)
  1274. case GT:
  1275. if rhs < 0 {
  1276. return true
  1277. }
  1278. return lhs > uint64(rhs)
  1279. case GTE:
  1280. if rhs < 0 {
  1281. return true
  1282. }
  1283. return lhs >= uint64(rhs)
  1284. case ADD:
  1285. return lhs + uint64(rhs)
  1286. case SUB:
  1287. return lhs - uint64(rhs)
  1288. case MUL:
  1289. return lhs * uint64(rhs)
  1290. case DIV:
  1291. if rhs == 0 {
  1292. return fmt.Errorf("divided by zero")
  1293. }
  1294. return lhs / uint64(rhs)
  1295. case MOD:
  1296. if rhs == 0 {
  1297. return fmt.Errorf("divided by zero")
  1298. }
  1299. return lhs % uint64(rhs)
  1300. case BITWISE_AND:
  1301. return lhs & uint64(rhs)
  1302. case BITWISE_OR:
  1303. return lhs | uint64(rhs)
  1304. case BITWISE_XOR:
  1305. return lhs ^ uint64(rhs)
  1306. default:
  1307. return invalidOpError(lhs, op, rhs)
  1308. }
  1309. case uint64:
  1310. switch op {
  1311. case EQ:
  1312. return lhs == rhs
  1313. case NEQ:
  1314. return lhs != rhs
  1315. case LT:
  1316. return lhs < rhs
  1317. case LTE:
  1318. return lhs <= rhs
  1319. case GT:
  1320. return lhs > rhs
  1321. case GTE:
  1322. return lhs >= rhs
  1323. case ADD:
  1324. return lhs + rhs
  1325. case SUB:
  1326. return lhs - rhs
  1327. case MUL:
  1328. return lhs * rhs
  1329. case DIV:
  1330. if rhs == 0 {
  1331. return fmt.Errorf("divided by zero")
  1332. }
  1333. return lhs / rhs
  1334. case MOD:
  1335. if rhs == 0 {
  1336. return fmt.Errorf("divided by zero")
  1337. }
  1338. return lhs % rhs
  1339. case BITWISE_AND:
  1340. return lhs & rhs
  1341. case BITWISE_OR:
  1342. return lhs | rhs
  1343. case BITWISE_XOR:
  1344. return lhs ^ rhs
  1345. default:
  1346. return invalidOpError(lhs, op, rhs)
  1347. }
  1348. default:
  1349. return invalidOpError(lhs, op, rhs)
  1350. }
  1351. case string:
  1352. rhss, ok := rhs.(string)
  1353. if !ok {
  1354. return invalidOpError(lhs, op, rhs)
  1355. }
  1356. switch op {
  1357. case EQ:
  1358. return lhs == rhss
  1359. case NEQ:
  1360. return lhs != rhss
  1361. case LT:
  1362. return lhs < rhss
  1363. case LTE:
  1364. return lhs <= rhss
  1365. case GT:
  1366. return lhs > rhss
  1367. case GTE:
  1368. return lhs >= rhss
  1369. default:
  1370. return invalidOpError(lhs, op, rhs)
  1371. }
  1372. case time.Time:
  1373. rt, err := common.InterfaceToTime(rhs, "")
  1374. if err != nil {
  1375. return invalidOpError(lhs, op, rhs)
  1376. }
  1377. switch op {
  1378. case EQ:
  1379. return lhs.Equal(rt)
  1380. case NEQ:
  1381. return !lhs.Equal(rt)
  1382. case LT:
  1383. return lhs.Before(rt)
  1384. case LTE:
  1385. return lhs.Before(rt) || lhs.Equal(rt)
  1386. case GT:
  1387. return lhs.After(rt)
  1388. case GTE:
  1389. return lhs.After(rt) || lhs.Equal(rt)
  1390. default:
  1391. return invalidOpError(lhs, op, rhs)
  1392. }
  1393. default:
  1394. return invalidOpError(lhs, op, rhs)
  1395. }
  1396. return invalidOpError(lhs, op, rhs)
  1397. }
  1398. func invalidOpError(lhs interface{}, op Token, rhs interface{}) error {
  1399. return fmt.Errorf("invalid operation %[1]T(%[1]v) %s %[3]T(%[3]v)", lhs, tokens[op], rhs)
  1400. }
  1401. func convertNum(para interface{}) interface{} {
  1402. if isInt(para) {
  1403. para = toInt64(para)
  1404. } else if isFloat(para) {
  1405. para = toFloat64(para)
  1406. }
  1407. return para
  1408. }
  1409. func isInt(para interface{}) bool {
  1410. switch para.(type) {
  1411. case int:
  1412. return true
  1413. case int8:
  1414. return true
  1415. case int16:
  1416. return true
  1417. case int32:
  1418. return true
  1419. case int64:
  1420. return true
  1421. }
  1422. return false
  1423. }
  1424. func toInt64(para interface{}) int64 {
  1425. if v, ok := para.(int); ok {
  1426. return int64(v)
  1427. } else if v, ok := para.(int8); ok {
  1428. return int64(v)
  1429. } else if v, ok := para.(int16); ok {
  1430. return int64(v)
  1431. } else if v, ok := para.(int32); ok {
  1432. return int64(v)
  1433. } else if v, ok := para.(int64); ok {
  1434. return v
  1435. }
  1436. return 0
  1437. }
  1438. func isFloat(para interface{}) bool {
  1439. switch para.(type) {
  1440. case float32:
  1441. return true
  1442. case float64:
  1443. return true
  1444. }
  1445. return false
  1446. }
  1447. func toFloat64(para interface{}) float64 {
  1448. if v, ok := para.(float32); ok {
  1449. return float64(v)
  1450. } else if v, ok := para.(float64); ok {
  1451. return v
  1452. }
  1453. return 0
  1454. }
  1455. func IsAggStatement(node Node) bool {
  1456. var r = false
  1457. WalkFunc(node, func(n Node) {
  1458. if f, ok := n.(*Call); ok {
  1459. if ok := isAggFunc(f); ok {
  1460. r = true
  1461. return
  1462. }
  1463. } else if d, ok := n.(Dimensions); ok {
  1464. ds := d.GetGroups()
  1465. if ds != nil && len(ds) > 0 {
  1466. r = true
  1467. return
  1468. }
  1469. }
  1470. })
  1471. return r
  1472. }
  1473. func isAggFunc(f *Call) bool {
  1474. fn := strings.ToLower(f.Name)
  1475. if _, ok := aggFuncMap[fn]; ok {
  1476. return true
  1477. } else if _, ok := strFuncMap[fn]; ok {
  1478. return false
  1479. } else if _, ok := convFuncMap[fn]; ok {
  1480. return false
  1481. } else if _, ok := hashFuncMap[fn]; ok {
  1482. return false
  1483. } else if _, ok := otherFuncMap[fn]; ok {
  1484. return false
  1485. } else if _, ok := mathFuncMap[fn]; ok {
  1486. return false
  1487. } else {
  1488. if nf, err := plugins.GetPlugin(f.Name, plugins.FUNCTION); err == nil {
  1489. if ef, ok := nf.(api.Function); ok && ef.IsAggregate() {
  1490. return true
  1491. }
  1492. }
  1493. }
  1494. return false
  1495. }
  1496. func HasAggFuncs(node Node) bool {
  1497. if node == nil {
  1498. return false
  1499. }
  1500. var r = false
  1501. WalkFunc(node, func(n Node) {
  1502. if f, ok := n.(*Call); ok {
  1503. if ok := isAggFunc(f); ok {
  1504. r = true
  1505. return
  1506. }
  1507. }
  1508. })
  1509. return r
  1510. }
  1511. func HasNoAggFuncs(node Node) bool {
  1512. if node == nil {
  1513. return false
  1514. }
  1515. var r = false
  1516. WalkFunc(node, func(n Node) {
  1517. if f, ok := n.(*Call); ok {
  1518. if ok := isAggFunc(f); !ok {
  1519. r = true
  1520. return
  1521. }
  1522. }
  1523. })
  1524. return r
  1525. }