ReplaceTable returns a Rule that replaces all occurrences of a table name throughout a SELECT, UPDATE, or DELETE statement. The replacement covers: - FROM clause table references - JOIN clause left and right table references - Column qualifiers (table.column identifiers in SELECT list, WHERE, ORDER
(oldName, newName string)
| 37 | // |
| 38 | // Returns ErrUnsupportedStatement for INSERT or DDL statements. |
| 39 | func ReplaceTable(oldName, newName string) Rule { |
| 40 | return RuleFunc(func(stmt ast.Statement) error { |
| 41 | switch s := stmt.(type) { |
| 42 | case *ast.SelectStatement: |
| 43 | replaceTableInFrom(s.From, oldName, newName) |
| 44 | replaceTableInJoins(s.Joins, oldName, newName) |
| 45 | for i, col := range s.Columns { |
| 46 | s.Columns[i] = replaceTableInExpr(col, oldName, newName) |
| 47 | } |
| 48 | s.Where = replaceTableInExpr(s.Where, oldName, newName) |
| 49 | for i, ob := range s.OrderBy { |
| 50 | s.OrderBy[i].Expression = replaceTableInExpr(ob.Expression, oldName, newName) |
| 51 | } |
| 52 | return nil |
| 53 | case *ast.UpdateStatement: |
| 54 | if strings.EqualFold(s.TableName, oldName) { |
| 55 | s.TableName = newName |
| 56 | } |
| 57 | s.Where = replaceTableInExpr(s.Where, oldName, newName) |
| 58 | return nil |
| 59 | case *ast.DeleteStatement: |
| 60 | if strings.EqualFold(s.TableName, oldName) { |
| 61 | s.TableName = newName |
| 62 | } |
| 63 | s.Where = replaceTableInExpr(s.Where, oldName, newName) |
| 64 | return nil |
| 65 | default: |
| 66 | return &ErrUnsupportedStatement{Transform: "ReplaceTable", Got: stmtTypeName(stmt)} |
| 67 | } |
| 68 | }) |
| 69 | } |
| 70 | |
| 71 | // AddTableAlias returns a Rule that assigns an alias to a specific table in a |
| 72 | // SELECT, UPDATE, or DELETE statement. For SELECT statements the alias is applied |