RewriteSqlSource this Source to act as a stand-alone query to backend @parentStmt = the parent statement that this a partial source to
(m *SqlSource, parentStmt *SqlSelect)
| 25 | // RewriteSqlSource this Source to act as a stand-alone query to backend |
| 26 | // @parentStmt = the parent statement that this a partial source to |
| 27 | func RewriteSqlSource(m *SqlSource, parentStmt *SqlSelect) *SqlSelect { |
| 28 | |
| 29 | if m.Source != nil { |
| 30 | return m.Source |
| 31 | } |
| 32 | // Rewrite this SqlSource for the given parent, ie |
| 33 | // 1) find the column names we need to request from source including those used in join/where |
| 34 | // 2) rewrite the where for this partial query |
| 35 | // 3) any columns in join expression that are not equal between |
| 36 | // sides should be aliased towards the left-hand join portion |
| 37 | // 4) if we need different sort for our join algo? |
| 38 | |
| 39 | newCols := make(Columns, 0) |
| 40 | if !parentStmt.Star { |
| 41 | for idx, col := range parentStmt.Columns { |
| 42 | left, _, hasLeft := col.LeftRight() |
| 43 | if !hasLeft { |
| 44 | // Was not left/right qualified, so use as is? or is this an error? |
| 45 | // what is official sql grammar on this? |
| 46 | newCol := col.Copy() |
| 47 | newCol.ParentIndex = idx |
| 48 | newCol.Index = len(newCols) |
| 49 | newCols = append(newCols, newCol) |
| 50 | |
| 51 | } else if hasLeft && left == m.Alias { |
| 52 | newCol := col.CopyRewrite(m.Alias) |
| 53 | newCol.ParentIndex = idx |
| 54 | newCol.SourceIndex = len(newCols) |
| 55 | newCol.Index = len(newCols) |
| 56 | newCols = append(newCols, newCol) |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | // TODO: |
| 62 | // - rewrite the Sort |
| 63 | // - rewrite the group-by |
| 64 | sql2 := &SqlSelect{Columns: newCols, Star: parentStmt.Star} |
| 65 | m.joinNodes = make([]expr.Node, 0) |
| 66 | if m.SubQuery != nil { |
| 67 | if len(m.SubQuery.From) != 1 { |
| 68 | u.Errorf("Not supported, nested subQuery %v", m.SubQuery.String()) |
| 69 | } else { |
| 70 | sql2.From = append(sql2.From, &SqlSource{Name: m.SubQuery.From[0].Name}) |
| 71 | } |
| 72 | } else { |
| 73 | sql2.From = append(sql2.From, &SqlSource{Name: m.Name}) |
| 74 | } |
| 75 | |
| 76 | for _, from := range parentStmt.From { |
| 77 | // We need to check each participant in the Join for possible |
| 78 | // columns which need to be re-written |
| 79 | sql2.Columns = columnsFromJoin(m, from.JoinExpr, sql2.Columns) |
| 80 | |
| 81 | // We also need to create an expression used for evaluating |
| 82 | // the values of Join "Keys" |
| 83 | if from.JoinExpr != nil { |
| 84 | joinNodesForFrom(parentStmt, m, from.JoinExpr, 0) |
no test coverage detected