analyzer.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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 planner
  15. import (
  16. "fmt"
  17. "sort"
  18. "strings"
  19. "github.com/lf-edge/ekuiper/internal/binder/function"
  20. "github.com/lf-edge/ekuiper/internal/schema"
  21. "github.com/lf-edge/ekuiper/internal/xsql"
  22. "github.com/lf-edge/ekuiper/pkg/ast"
  23. "github.com/lf-edge/ekuiper/pkg/kv"
  24. )
  25. type streamInfo struct {
  26. stmt *ast.StreamStmt
  27. schema ast.StreamFields
  28. }
  29. // Analyze the select statement by decorating the info from stream statement.
  30. // Typically, set the correct stream name for fieldRefs
  31. func decorateStmt(s *ast.SelectStatement, store kv.KeyValue) ([]*streamInfo, []*ast.Call, []*ast.Call, error) {
  32. streamsFromStmt := xsql.GetStreams(s)
  33. streamStmts := make([]*streamInfo, len(streamsFromStmt))
  34. isSchemaless := false
  35. for i, s := range streamsFromStmt {
  36. streamStmt, err := xsql.GetDataSource(store, s)
  37. if err != nil {
  38. return nil, nil, nil, fmt.Errorf("fail to get stream %s, please check if stream is created", s)
  39. }
  40. si, err := convertStreamInfo(streamStmt)
  41. if err != nil {
  42. return nil, nil, nil, err
  43. }
  44. streamStmts[i] = si
  45. if si.schema == nil {
  46. isSchemaless = true
  47. }
  48. }
  49. if checkAliasReferenceCycle(s) {
  50. return nil, nil, nil, fmt.Errorf("select fields have cycled alias")
  51. }
  52. if !isSchemaless {
  53. if err := aliasFieldTopoSort(s, streamStmts); err != nil {
  54. return nil, nil, nil, err
  55. }
  56. }
  57. dsn := ast.DefaultStream
  58. if len(streamsFromStmt) == 1 {
  59. dsn = streamStmts[0].stmt.Name
  60. }
  61. // [fieldName][streamsName][*aliasRef] if alias, with special key alias/default. Each key has exactly one value
  62. fieldsMap := newFieldsMap(isSchemaless, dsn)
  63. if !isSchemaless {
  64. for _, streamStmt := range streamStmts {
  65. for _, field := range streamStmt.schema {
  66. fieldsMap.reserve(field.Name, streamStmt.stmt.Name)
  67. }
  68. }
  69. }
  70. var (
  71. walkErr error
  72. aliasFields []*ast.Field
  73. analyticFieldFuncs []*ast.Call
  74. analyticFuncs []*ast.Call
  75. )
  76. // Scan columns fields: bind all field refs, collect alias
  77. for i, f := range s.Fields {
  78. ast.WalkFunc(f.Expr, func(n ast.Node) bool {
  79. switch f := n.(type) {
  80. case *ast.FieldRef:
  81. walkErr = fieldsMap.bind(f)
  82. }
  83. return true
  84. })
  85. if walkErr != nil {
  86. return nil, nil, nil, walkErr
  87. }
  88. if f.AName != "" {
  89. aliasFields = append(aliasFields, &s.Fields[i])
  90. fieldsMap.bindAlias(f.AName)
  91. }
  92. }
  93. // bind alias field expressions
  94. for _, f := range aliasFields {
  95. ar, err := ast.NewAliasRef(f.Expr)
  96. if err != nil {
  97. walkErr = err
  98. } else {
  99. f.Expr = &ast.FieldRef{
  100. StreamName: ast.AliasStream,
  101. Name: f.AName,
  102. AliasRef: ar,
  103. }
  104. walkErr = fieldsMap.save(f.AName, ast.AliasStream, ar)
  105. for _, subF := range s.Fields {
  106. if f.AName == subF.AName {
  107. continue
  108. }
  109. ast.WalkFunc(&subF, func(node ast.Node) bool {
  110. switch fr := node.(type) {
  111. case *ast.FieldRef:
  112. if fr.Name == f.AName {
  113. fr.StreamName = ast.AliasStream
  114. fr.AliasRef = ar
  115. }
  116. return false
  117. }
  118. return true
  119. })
  120. }
  121. }
  122. }
  123. // Bind field ref for alias AND set StreamName for all field ref
  124. ast.WalkFunc(s, func(n ast.Node) bool {
  125. switch f := n.(type) {
  126. case ast.Fields: // do not bind selection fields, should have done above
  127. return false
  128. case *ast.FieldRef:
  129. if f.StreamName != "" && f.StreamName != ast.DefaultStream {
  130. // check if stream exists
  131. found := false
  132. for _, sn := range streamsFromStmt {
  133. if sn == string(f.StreamName) {
  134. found = true
  135. break
  136. }
  137. }
  138. if !found {
  139. walkErr = fmt.Errorf("stream %s not found", f.StreamName)
  140. return true
  141. }
  142. }
  143. walkErr = fieldsMap.bind(f)
  144. }
  145. return true
  146. })
  147. if walkErr != nil {
  148. return nil, nil, nil, walkErr
  149. }
  150. walkErr = validate(s)
  151. // Collect all analytic function calls so that we can let them run firstly
  152. ast.WalkFunc(s, func(n ast.Node) bool {
  153. switch f := n.(type) {
  154. case ast.Fields:
  155. return false
  156. case *ast.Call:
  157. if function.IsAnalyticFunc(f.Name) {
  158. f.CachedField = fmt.Sprintf("%s_%s_%d", function.AnalyticPrefix, f.Name, f.FuncId)
  159. f.Cached = true
  160. analyticFuncs = append(analyticFuncs, &ast.Call{
  161. Name: f.Name,
  162. FuncId: f.FuncId,
  163. FuncType: f.FuncType,
  164. Args: f.Args,
  165. CachedField: f.CachedField,
  166. Partition: f.Partition,
  167. WhenExpr: f.WhenExpr,
  168. })
  169. }
  170. }
  171. return true
  172. })
  173. if walkErr != nil {
  174. return nil, nil, nil, walkErr
  175. }
  176. // walk sources at last to let them run firstly
  177. // because another clause may depend on the alias defined here
  178. for _, field := range s.Fields {
  179. var calls []*ast.Call
  180. ast.WalkFunc(&field, func(n ast.Node) bool {
  181. switch f := n.(type) {
  182. case *ast.Call:
  183. if function.IsAnalyticFunc(f.Name) {
  184. f.CachedField = fmt.Sprintf("%s_%s_%d", function.AnalyticPrefix, f.Name, f.FuncId)
  185. f.Cached = true
  186. calls = append([]*ast.Call{
  187. {
  188. Name: f.Name,
  189. FuncId: f.FuncId,
  190. FuncType: f.FuncType,
  191. Args: f.Args,
  192. CachedField: f.CachedField,
  193. Partition: f.Partition,
  194. WhenExpr: f.WhenExpr,
  195. },
  196. }, calls...)
  197. }
  198. }
  199. return true
  200. })
  201. analyticFieldFuncs = append(analyticFieldFuncs, calls...)
  202. }
  203. if walkErr != nil {
  204. return nil, nil, nil, walkErr
  205. }
  206. return streamStmts, analyticFuncs, analyticFieldFuncs, walkErr
  207. }
  208. type aliasTopoDegree struct {
  209. alias string
  210. degree int
  211. field ast.Field
  212. }
  213. type aliasTopoDegrees []*aliasTopoDegree
  214. func (a aliasTopoDegrees) Len() int {
  215. return len(a)
  216. }
  217. func (a aliasTopoDegrees) Less(i, j int) bool {
  218. if a[i].degree == a[j].degree {
  219. return a[i].alias < a[j].alias
  220. }
  221. return a[i].degree < a[j].degree
  222. }
  223. func (a aliasTopoDegrees) Swap(i, j int) {
  224. a[i], a[j] = a[j], a[i]
  225. }
  226. // checkAliasReferenceCycle checks whether exists select a + 1 as b, b + 1 as a from demo;
  227. func checkAliasReferenceCycle(s *ast.SelectStatement) bool {
  228. aliasRef := make(map[string]map[string]struct{})
  229. for _, field := range s.Fields {
  230. if len(field.AName) > 0 {
  231. aliasRef[field.AName] = make(map[string]struct{})
  232. }
  233. }
  234. if len(aliasRef) < 1 {
  235. return false
  236. }
  237. hasCycleAlias := false
  238. for _, field := range s.Fields {
  239. if len(field.AName) > 0 {
  240. ast.WalkFunc(&field, func(node ast.Node) bool {
  241. switch f := node.(type) {
  242. case *ast.FieldRef:
  243. if len(f.Name) > 0 {
  244. if f.Name == field.AName {
  245. return true
  246. }
  247. _, ok := aliasRef[f.Name]
  248. if ok {
  249. aliasRef[field.AName][f.Name] = struct{}{}
  250. if dfsRef(aliasRef, map[string]struct{}{}, f.Name, field.AName) {
  251. hasCycleAlias = true
  252. return false
  253. }
  254. }
  255. }
  256. }
  257. return true
  258. })
  259. if hasCycleAlias {
  260. return true
  261. }
  262. }
  263. }
  264. return false
  265. }
  266. func dfsRef(aliasRef map[string]map[string]struct{}, walked map[string]struct{}, currentName, targetName string) bool {
  267. defer func() {
  268. walked[currentName] = struct{}{}
  269. }()
  270. for refName := range aliasRef[currentName] {
  271. if refName == targetName {
  272. return true
  273. }
  274. }
  275. for name := range aliasRef[currentName] {
  276. _, ok := walked[name]
  277. if ok {
  278. continue
  279. }
  280. if dfsRef(aliasRef, walked, name, targetName) {
  281. return true
  282. }
  283. }
  284. return false
  285. }
  286. func aliasFieldTopoSort(s *ast.SelectStatement, streamStmts []*streamInfo) error {
  287. nonAliasFields := make([]ast.Field, 0)
  288. aliasDegreeMap := make(map[string]*aliasTopoDegree)
  289. for _, field := range s.Fields {
  290. if field.AName != "" {
  291. aliasDegreeMap[field.AName] = &aliasTopoDegree{
  292. alias: field.AName,
  293. degree: -1,
  294. field: field,
  295. }
  296. } else {
  297. nonAliasFields = append(nonAliasFields, field)
  298. }
  299. }
  300. for !isAliasFieldTopoSortFinish(aliasDegreeMap) {
  301. for _, field := range s.Fields {
  302. if field.AName != "" && aliasDegreeMap[field.AName].degree < 0 {
  303. unknownFieldRefName := ""
  304. degree := 0
  305. ast.WalkFunc(field.Expr, func(node ast.Node) bool {
  306. switch f := node.(type) {
  307. case *ast.FieldRef:
  308. if fDegree, ok := aliasDegreeMap[f.Name]; ok && fDegree.degree >= 0 {
  309. if degree < fDegree.degree+1 {
  310. degree = fDegree.degree + 1
  311. }
  312. return true
  313. }
  314. if !isFieldRefNameExists(f.Name, streamStmts) {
  315. unknownFieldRefName = f.Name
  316. return false
  317. }
  318. }
  319. return true
  320. })
  321. if len(unknownFieldRefName) > 0 {
  322. unknownField := true
  323. for _, otherField := range s.Fields {
  324. if field == otherField {
  325. continue
  326. }
  327. // the unknownFieldRef name belongs to a alias
  328. if otherField.AName == unknownFieldRefName {
  329. unknownField = false
  330. break
  331. }
  332. }
  333. if unknownField {
  334. return fmt.Errorf("unknown field %s", unknownFieldRefName)
  335. }
  336. }
  337. aliasDegreeMap[field.AName].degree = degree
  338. }
  339. }
  340. }
  341. as := make(aliasTopoDegrees, 0)
  342. for _, degree := range aliasDegreeMap {
  343. as = append(as, degree)
  344. }
  345. sort.Sort(as)
  346. s.Fields = make([]ast.Field, 0)
  347. for _, d := range as {
  348. s.Fields = append(s.Fields, d.field)
  349. }
  350. s.Fields = append(s.Fields, nonAliasFields...)
  351. return nil
  352. }
  353. func isFieldRefNameExists(name string, streamStmts []*streamInfo) bool {
  354. for _, streamStmt := range streamStmts {
  355. for _, col := range streamStmt.schema {
  356. if col.Name == name {
  357. return true
  358. }
  359. }
  360. }
  361. return false
  362. }
  363. func isAliasFieldTopoSortFinish(aliasDegrees map[string]*aliasTopoDegree) bool {
  364. for _, aliasDegree := range aliasDegrees {
  365. if aliasDegree.degree < 0 {
  366. return false
  367. }
  368. }
  369. return true
  370. }
  371. func validate(s *ast.SelectStatement) (err error) {
  372. isAggStmt := false
  373. if xsql.IsAggregate(s.Condition) {
  374. return fmt.Errorf("Not allowed to call aggregate functions in WHERE clause.")
  375. }
  376. if !allAggregate(s.Having) {
  377. return fmt.Errorf("Not allowed to call non-aggregate functions in HAVING clause.")
  378. }
  379. for _, d := range s.Dimensions {
  380. isAggStmt = true
  381. if xsql.IsAggregate(d.Expr) {
  382. return fmt.Errorf("Not allowed to call aggregate functions in GROUP BY clause.")
  383. }
  384. }
  385. if s.Joins != nil {
  386. isAggStmt = true
  387. }
  388. ast.WalkFunc(s, func(n ast.Node) bool {
  389. switch f := n.(type) {
  390. case *ast.Call:
  391. // aggregate call should not have any aggregate arg
  392. if function.IsAggFunc(f.Name) {
  393. for _, arg := range f.Args {
  394. tr := xsql.IsAggregate(arg)
  395. if tr {
  396. err = fmt.Errorf("invalid argument for func %s: aggregate argument is not allowed", f.Name)
  397. return false
  398. }
  399. }
  400. }
  401. if isAggStmt && function.NoAggFunc(f.Name) {
  402. err = fmt.Errorf("function %s is not allowed in an aggregate query", f.Name)
  403. return false
  404. }
  405. case *ast.Window:
  406. // agg func check is done in dimensions.
  407. // in window trigger condition, NoAggFunc is allowed unlike normal condition so return false to skip that check
  408. return false
  409. }
  410. return true
  411. })
  412. return
  413. }
  414. // file-private functions below
  415. // allAggregate checks if all expressions of binary expression are aggregate
  416. func allAggregate(expr ast.Expr) (r bool) {
  417. r = true
  418. ast.WalkFunc(expr, func(n ast.Node) bool {
  419. switch f := expr.(type) {
  420. case *ast.BinaryExpr:
  421. switch f.OP {
  422. case ast.SUBSET, ast.ARROW:
  423. // do nothing
  424. default:
  425. r = allAggregate(f.LHS) && allAggregate(f.RHS)
  426. return false
  427. }
  428. case *ast.Call, *ast.FieldRef:
  429. if !xsql.IsAggregate(f) {
  430. r = false
  431. return false
  432. }
  433. }
  434. return true
  435. })
  436. return
  437. }
  438. func convertStreamInfo(streamStmt *ast.StreamStmt) (*streamInfo, error) {
  439. ss := streamStmt.StreamFields
  440. var err error
  441. if streamStmt.Options.SCHEMAID != "" {
  442. ss, err = schema.InferFromSchemaFile(streamStmt.Options.FORMAT, streamStmt.Options.SCHEMAID)
  443. if err != nil {
  444. return nil, err
  445. }
  446. }
  447. return &streamInfo{
  448. stmt: streamStmt,
  449. schema: ss,
  450. }, nil
  451. }
  452. type fieldsMap struct {
  453. content map[string]streamFieldStore
  454. aliasNames map[string]struct{}
  455. isSchemaless bool
  456. defaultStream ast.StreamName
  457. }
  458. func newFieldsMap(isSchemaless bool, defaultStream ast.StreamName) *fieldsMap {
  459. return &fieldsMap{content: make(map[string]streamFieldStore), aliasNames: map[string]struct{}{}, isSchemaless: isSchemaless, defaultStream: defaultStream}
  460. }
  461. func (f *fieldsMap) reserve(fieldName string, streamName ast.StreamName) {
  462. lname := strings.ToLower(fieldName)
  463. if fm, ok := f.content[lname]; ok {
  464. fm.add(streamName)
  465. } else {
  466. fm := newStreamFieldStore(f.isSchemaless, f.defaultStream)
  467. fm.add(streamName)
  468. f.content[lname] = fm
  469. }
  470. }
  471. func (f *fieldsMap) save(fieldName string, streamName ast.StreamName, field *ast.AliasRef) error {
  472. lname := strings.ToLower(fieldName)
  473. fm, ok := f.content[lname]
  474. if !ok {
  475. if streamName == ast.AliasStream || f.isSchemaless {
  476. fm = newStreamFieldStore(f.isSchemaless, f.defaultStream)
  477. f.content[lname] = fm
  478. } else {
  479. return fmt.Errorf("unknown field %s", fieldName)
  480. }
  481. }
  482. err := fm.ref(streamName, field)
  483. if err != nil {
  484. return fmt.Errorf("%s%s", err, fieldName)
  485. }
  486. return nil
  487. }
  488. func (f *fieldsMap) bindAlias(aliasName string) {
  489. f.aliasNames[aliasName] = struct{}{}
  490. }
  491. func (f *fieldsMap) bind(fr *ast.FieldRef) error {
  492. lname := strings.ToLower(fr.Name)
  493. fm, ok1 := f.content[lname]
  494. _, ok2 := f.aliasNames[lname]
  495. if !ok1 && !ok2 {
  496. if f.isSchemaless && fr.Name != "" {
  497. fm = newStreamFieldStore(f.isSchemaless, f.defaultStream)
  498. f.content[lname] = fm
  499. } else {
  500. return fmt.Errorf("unknown field %s", fr.Name)
  501. }
  502. }
  503. if fm != nil {
  504. err := fm.bindRef(fr)
  505. if err != nil {
  506. return fmt.Errorf("%s%s", err, fr.Name)
  507. }
  508. }
  509. return nil
  510. }
  511. type streamFieldStore interface {
  512. add(k ast.StreamName)
  513. ref(k ast.StreamName, v *ast.AliasRef) error
  514. bindRef(f *ast.FieldRef) error
  515. }
  516. func newStreamFieldStore(isSchemaless bool, defaultStream ast.StreamName) streamFieldStore {
  517. if !isSchemaless {
  518. return &streamFieldMap{content: make(map[ast.StreamName]*ast.AliasRef)}
  519. } else {
  520. return &streamFieldMapSchemaless{content: make(map[ast.StreamName]*ast.AliasRef), defaultStream: defaultStream}
  521. }
  522. }
  523. type streamFieldMap struct {
  524. content map[ast.StreamName]*ast.AliasRef
  525. }
  526. // add the stream name must not be default.
  527. // This is used when traversing stream schema
  528. func (s *streamFieldMap) add(k ast.StreamName) {
  529. s.content[k] = nil
  530. }
  531. // bind for schema field, all keys must be created before running bind
  532. // can bind alias & col. For alias, the stream name must be empty; For col, the field must be a col
  533. func (s *streamFieldMap) ref(k ast.StreamName, v *ast.AliasRef) error {
  534. if k == ast.AliasStream { // must not exist, save alias ref for alias
  535. _, ok := s.content[k]
  536. if ok {
  537. return fmt.Errorf("duplicate alias ")
  538. }
  539. s.content[k] = v
  540. } else { // the key must exist after the schema travers, do validation
  541. if k == ast.DefaultStream { // In schema mode, default stream won't be a key
  542. l := len(s.content)
  543. if l == 0 {
  544. return fmt.Errorf("unknow field ")
  545. } else if l == 1 {
  546. // valid, do nothing
  547. } else {
  548. return fmt.Errorf("ambiguous field ")
  549. }
  550. } else {
  551. _, ok := s.content[k]
  552. if !ok {
  553. return fmt.Errorf("unknow field %s.", k)
  554. }
  555. }
  556. }
  557. return nil
  558. }
  559. func (s *streamFieldMap) bindRef(fr *ast.FieldRef) error {
  560. l := len(s.content)
  561. if fr.StreamName == "" {
  562. fr.StreamName = ast.DefaultStream
  563. }
  564. k := fr.StreamName
  565. if k == ast.DefaultStream {
  566. switch l {
  567. case 0:
  568. return fmt.Errorf("unknown field ")
  569. case 1: // if alias, return this
  570. for sk, sv := range s.content {
  571. fr.RefSelection(sv)
  572. fr.StreamName = sk
  573. }
  574. return nil
  575. default:
  576. r, ok := s.content[ast.AliasStream] // if alias exists
  577. if ok {
  578. fr.RefSelection(r)
  579. fr.StreamName = ast.AliasStream
  580. return nil
  581. } else {
  582. return fmt.Errorf("ambiguous field ")
  583. }
  584. }
  585. } else {
  586. r, ok := s.content[k]
  587. if ok {
  588. fr.RefSelection(r)
  589. return nil
  590. } else {
  591. return fmt.Errorf("unknown field %s.", k)
  592. }
  593. }
  594. }
  595. type streamFieldMapSchemaless struct {
  596. content map[ast.StreamName]*ast.AliasRef
  597. defaultStream ast.StreamName
  598. }
  599. // add this should not be called for schemaless
  600. func (s *streamFieldMapSchemaless) add(k ast.StreamName) {
  601. s.content[k] = nil
  602. }
  603. // bind for schemaless field, create column if not exist
  604. // can bind alias & col. For alias, the stream name must be empty; For col, the field must be a col
  605. func (s *streamFieldMapSchemaless) ref(k ast.StreamName, v *ast.AliasRef) error {
  606. if k == ast.AliasStream { // must not exist
  607. _, ok := s.content[k]
  608. if ok {
  609. return fmt.Errorf("duplicate alias ")
  610. }
  611. s.content[k] = v
  612. } else { // the key may or may not exist. But always have only one default stream field.
  613. // Replace with stream name if another stream found. The key can be duplicate
  614. l := len(s.content)
  615. if k == ast.DefaultStream { // In schemaless mode, default stream can only exist when length is 1
  616. if l < 1 {
  617. // valid, do nothing
  618. } else {
  619. return fmt.Errorf("ambiguous field ")
  620. }
  621. } else {
  622. if l == 1 {
  623. for sk := range s.content {
  624. if sk == ast.DefaultStream {
  625. delete(s.content, k)
  626. }
  627. }
  628. }
  629. }
  630. }
  631. return nil
  632. }
  633. func (s *streamFieldMapSchemaless) bindRef(fr *ast.FieldRef) error {
  634. l := len(s.content)
  635. if fr.StreamName == "" || fr.StreamName == ast.DefaultStream {
  636. if l == 1 {
  637. for sk := range s.content {
  638. fr.StreamName = sk
  639. }
  640. }
  641. }
  642. k := fr.StreamName
  643. if k == ast.DefaultStream {
  644. switch l {
  645. case 0: // must be a column because alias are fields and have been traversed
  646. // reserve a hole and do nothing
  647. fr.StreamName = s.defaultStream
  648. s.content[s.defaultStream] = nil
  649. return nil
  650. case 1: // if alias or single col, return this
  651. for sk, sv := range s.content {
  652. fr.RefSelection(sv)
  653. fr.StreamName = sk
  654. }
  655. return nil
  656. default:
  657. r, ok := s.content[ast.AliasStream] // if alias exists
  658. if ok {
  659. fr.RefSelection(r)
  660. fr.StreamName = ast.AliasStream
  661. return nil
  662. } else {
  663. fr.StreamName = s.defaultStream
  664. }
  665. }
  666. }
  667. if fr.StreamName != ast.DefaultStream {
  668. r, ok := s.content[k]
  669. if !ok { // reserver a hole
  670. s.content[k] = nil
  671. } else {
  672. fr.RefSelection(r)
  673. }
  674. return nil
  675. }
  676. return fmt.Errorf("ambiguous field ")
  677. }