Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: partial support PG SELECT statement (#2056)
rebeliceaf873f9c7484
diff --git a/plugin/parser/ast/column_name_def.go b/plugin/parser/ast/column_name_def.gonew file mode 100644index 0000000000..431755855a--- /dev/null+++ b/plugin/parser/ast/column_name_def.go@@ -0,0 +1,9 @@+package ast++// ColumnNameDef is the struct for column name definition.+type ColumnNameDef struct {+ expression++ Table *TableDef+ ColumnName string+}diff --git a/plugin/parser/ast/expression_def.go b/plugin/parser/ast/expression_def.gonew file mode 100644index 0000000000..1053385c9b--- /dev/null+++ b/plugin/parser/ast/expression_def.go@@ -0,0 +1,19 @@+package ast++var (+ _ ExpressionNode = (*expression)(nil)+)++// ExpressionNode is the interface for expressions.+type ExpressionNode interface {+ Node++ expressionNode()+}++// expression is the base struct for expression nodes.+type expression struct {+ node+}++func (*expression) expressionNode() {}diff --git a/plugin/parser/ast/node.go b/plugin/parser/ast/node.goindex 3f758b88d3..17a17911e2 100644--- a/plugin/parser/ast/node.go+++ b/plugin/parser/ast/node.go@@ -1,5 +1,9 @@package ast+var (+ _ Node = (*node)(nil)+)+// Node is the interface for node.type Node interface {Text() stringdiff --git a/plugin/parser/ast/pattern_like_def.go b/plugin/parser/ast/pattern_like_def.gonew file mode 100644index 0000000000..9e1e0309ca--- /dev/null+++ b/plugin/parser/ast/pattern_like_def.go@@ -0,0 +1,10 @@+package ast++// PatternLikeDef is the struct for LIKE expression definition, e.g. a LIKE '%abc'.+type PatternLikeDef struct {+ expression++ Not bool+ Expression ExpressionNode+ Pattern ExpressionNode+}diff --git a/plugin/parser/ast/select_stmt.go b/plugin/parser/ast/select_stmt.gonew file mode 100644index 0000000000..c21c1a19f8--- /dev/null+++ b/plugin/parser/ast/select_stmt.go@@ -0,0 +1,46 @@+package ast++// SetOperationType is the type for set operations.+type SetOperationType int++const (+ // SetOperationTypeNone is the type for no set operation, which means a SELECT stmt.+ SetOperationTypeNone SetOperationType = iota+ // SetOperationTypeUnion is the type for UNION.+ SetOperationTypeUnion+ // SetOperationTypeIntersect is the type for INTERSECT.+ SetOperationTypeIntersect+ // SetOperationTypeExcept is the type for EXCEPT.+ SetOperationTypeExcept+)++// SelectStmt is the struct for select statement.+type SelectStmt struct {+ node++ // if SetOperation is SetOperationTypeNode:+ // LQuery and RQuery is nil and SELECT fields is useful+ // otherwise:+ // only use LQuery and RQuery+ SetOperation SetOperationType+ // LQuery and RQuery are used for set operation, such as UNION.+ // In this case, we define the SQL as:+ // LQuery UNION RQuery;+ // Easy to know, LQuery and RQuery are SELECT statement, also.+ // Details at https://www.postgresql.org/docs/current/sql-select.html+ LQuery *SelectStmt+ RQuery *SelectStmt++ // SELECT fields+ FieldList []ExpressionNode+ WhereClause ExpressionNode++ // TODO(rebelice): support all expression and remove them.+ // We define them because we cannot convert all expression now.+ // And we only need to check the following nodes currently.+ //+ // PatternLikeList is the list of the patternLike nodes.+ PatternLikeList []*PatternLikeDef+ // SubqueryList is the list of the subquery nodes.+ SubqueryList []*SubqueryDef+}diff --git a/plugin/parser/ast/string_def.go b/plugin/parser/ast/string_def.gonew file mode 100644index 0000000000..56734ebf21--- /dev/null+++ b/plugin/parser/ast/string_def.go@@ -0,0 +1,8 @@+package ast++// StringDef is the struct for string definition.+type StringDef struct {+ expression++ Value string+}diff --git a/plugin/parser/ast/subquery_def.go b/plugin/parser/ast/subquery_def.gonew file mode 100644index 0000000000..14eaf59ebb--- /dev/null+++ b/plugin/parser/ast/subquery_def.go@@ -0,0 +1,8 @@+package ast++// SubqueryDef is the struct for subquery definition.+type SubqueryDef struct {+ expression++ Select *SelectStmt+}diff --git a/plugin/parser/ast/unconverted_expression_def.go b/plugin/parser/ast/unconverted_expression_def.gonew file mode 100644index 0000000000..c7027a5e72--- /dev/null+++ b/plugin/parser/ast/unconverted_expression_def.go@@ -0,0 +1,8 @@+package ast++// UnconvertedExpressionDef is the struct for unconveted expression definition.+// TODO(rebelice): remove it.+// We define this because we can not convert all expression types now.+type UnconvertedExpressionDef struct {+ expression+}diff --git a/plugin/parser/engine/pg/convert.go b/plugin/parser/engine/pg/convert.goindex 3c06b08cba..3dfc46b5fa 100644--- a/plugin/parser/engine/pg/convert.go+++ b/plugin/parser/engine/pg/convert.go@@ -1,6 +1,8 @@package pgimport (+ "fmt"+"github.com/bytebase/bytebase/plugin/parser""github.com/bytebase/bytebase/plugin/parser/ast"pgquery "github.com/pganalyze/pg_query_go/v2"@@ -9,7 +11,7 @@ import (// convert converts the pg_query.Node to ast.Node.func convert(node *pgquery.Node, text string) (res ast.Node, err error) {defer func() {- if res != nil {+ if err == nil && res != nil {res.SetText(text)}}()@@ -196,11 +198,207 @@ func convert(node *pgquery.Node, text string) (res ast.Node, err error) {}return dropTable, nil}+ case *pgquery.Node_SelectStmt:+ return convertSelectStmt(in.SelectStmt)}return nil, nil}+func convertExpressionNode(node *pgquery.Node) (ast.ExpressionNode, []*ast.PatternLikeDef, []*ast.SubqueryDef, error) {+ if node == nil || node.Node == nil {+ return &ast.UnconvertedExpressionDef{}, nil, nil, nil+ }+ switch in := node.Node.(type) {+ case *pgquery.Node_AConst:+ return convertExpressionNode(in.AConst.Val)+ case *pgquery.Node_String_:+ return &ast.StringDef{Value: in.String_.Str}, nil, nil, nil+ case *pgquery.Node_ResTarget:+ return convertExpressionNode(in.ResTarget.Val)+ case *pgquery.Node_TypeCast:+ _, likeList, subqueryList, err := convertExpressionNode(in.TypeCast.Arg)+ if err != nil {+ return nil, nil, nil, err+ }+ return &ast.UnconvertedExpressionDef{}, likeList, subqueryList, nil+ case *pgquery.Node_ColumnRef:+ columnName := &ast.ColumnNameDef{Table: &ast.TableDef{}}+ list := in.ColumnRef.Fields+ // There are three cases for column name:+ // 1. schemaName.tableName.columnName+ // 2. tableName.columnName+ // 3. columnName+ // The pg parser will split them by ".", and use a list to define it.+ // So we need to consider this three cases.+ switch len(in.ColumnRef.Fields) {+ // schemaName.tableName.columName+ case 3:+ schema, ok := list[0].Node.(*pgquery.Node_String_)+ if !ok {+ return nil, nil, nil, parser.NewConvertErrorf("expected String but found %t", in.ColumnRef.Fields[2].Node)+ }+ columnName.Table.Schema = schema.String_.Str+ // need to convert tableName.columnName+ list = list[1:]+ fallthrough+ // tableName.columnName+ case 2:+ table, ok := list[0].Node.(*pgquery.Node_String_)+ if !ok {+ return nil, nil, nil, parser.NewConvertErrorf("expected String but found %t", in.ColumnRef.Fields[1].Node)+ }+ columnName.Table.Name = table.String_.Str+ // need to convert columnName+ list = list[1:]+ fallthrough+ // columnName+ case 1:+ switch column := list[0].Node.(type) {+ // column name+ case *pgquery.Node_String_:+ columnName.ColumnName = column.String_.Str+ // e.g. SELECT * FROM t;+ case *pgquery.Node_AStar:+ columnName.ColumnName = "*"+ default:+ return nil, nil, nil, parser.NewConvertErrorf("expected String or AStar but found %t", in.ColumnRef.Fields[0].Node)+ }+ default:+ return nil, nil, nil, parser.NewConvertErrorf("failed to convert ColumnRef, column name contains unexpected components: %v", in)+ }+ return columnName, nil, nil, nil+ case *pgquery.Node_FuncCall:+ var likeList []*ast.PatternLikeDef+ var subqueryList []*ast.SubqueryDef+ for _, arg := range in.FuncCall.Args {+ _, interLike, interSubquery, err := convertExpressionNode(arg)+ if err != nil {+ return nil, nil, nil, err+ }+ likeList = append(likeList, interLike...)+ subqueryList = append(subqueryList, interSubquery...)+ }+ return &ast.UnconvertedExpressionDef{}, likeList, subqueryList, nil+ case *pgquery.Node_AExpr:+ var likeList, interLike []*ast.PatternLikeDef+ var subqueryList, interSubquery []*ast.SubqueryDef+ var lExpr, rExpr ast.ExpressionNode+ var err error+ if in.AExpr.Lexpr != nil {+ if lExpr, interLike, interSubquery, err = convertExpressionNode(in.AExpr.Lexpr); err != nil {+ return nil, nil, nil, err+ }+ likeList = append(likeList, interLike...)+ subqueryList = append(subqueryList, interSubquery...)+ }+ if in.AExpr.Rexpr != nil {+ if rExpr, interLike, interSubquery, err = convertExpressionNode(in.AExpr.Rexpr); err != nil {+ return nil, nil, nil, err+ }+ likeList = append(likeList, interLike...)+ subqueryList = append(subqueryList, interSubquery...)+ }+ if len(in.AExpr.Name) == 1 {+ name, ok := in.AExpr.Name[0].Node.(*pgquery.Node_String_)+ if !ok {+ return nil, nil, nil, parser.NewConvertErrorf("expected String but found %t", in.AExpr.Name[0].Node)+ }+ switch name.String_.Str {+ // LIKE+ case operatorLike, operatorNotLike:+ like := &ast.PatternLikeDef{+ Not: (name.String_.Str == operatorNotLike),+ Expression: lExpr,+ Pattern: rExpr,+ }+ likeList = append(likeList, like)+ return like, likeList, interSubquery, nil+ }+ }+ return &ast.UnconvertedExpressionDef{}, likeList, subqueryList, nil+ case *pgquery.Node_BoolExpr:+ var likeList []*ast.PatternLikeDef+ var subqueryList []*ast.SubqueryDef+ for _, arg := range in.BoolExpr.Args {+ _, interLike, interSubquery, err := convertExpressionNode(arg)+ if err != nil {+ return nil, nil, nil, err+ }+ likeList = append(likeList, interLike...)+ subqueryList = append(subqueryList, interSubquery...)+ }+ return &ast.UnconvertedExpressionDef{}, likeList, subqueryList, nil+ case *pgquery.Node_SubLink:+ if subselectNode, ok := in.SubLink.Subselect.Node.(*pgquery.Node_SelectStmt); ok {+ subselect, err := convertSelectStmt(subselectNode.SelectStmt)+ if err != nil {+ return nil, nil, nil, err+ }+ subQuery := &ast.SubqueryDef{Select: subselect}+ return subQuery, nil, []*ast.SubqueryDef{subQuery}, nil+ }+ }+ return &ast.UnconvertedExpressionDef{}, nil, nil, nil+}++func convertSelectStmt(in *pgquery.SelectStmt) (*ast.SelectStmt, error) {+ selectStmt := &ast.SelectStmt{}++ setOperation, err := convertSetOperation(in.Op)+ if err != nil {+ return nil, err+ }++ selectStmt.SetOperation = setOperation+ if setOperation != ast.SetOperationTypeNone {+ lQuery, err := convertSelectStmt(in.Larg)+ if err != nil {+ return nil, err+ }+ rQuery, err := convertSelectStmt(in.Rarg)+ if err != nil {+ return nil, err+ }+ selectStmt.LQuery = lQuery+ selectStmt.RQuery = rQuery+ return selectStmt, nil+ }++ // Convert target list+ for _, node := range in.TargetList {+ convertedNode, _, _, err := convertExpressionNode(node)+ if err != nil {+ return nil, err+ }+ selectStmt.FieldList = append(selectStmt.FieldList, convertedNode)+ }+ // Convert WHERE clause+ if in.WhereClause != nil {+ selectStmt.WhereClause = &ast.UnconvertedExpressionDef{}+ var err error+ if selectStmt.WhereClause, selectStmt.PatternLikeList, selectStmt.SubqueryList, err = convertExpressionNode(in.WhereClause); err != nil {+ return nil, err+ }+ }+ return selectStmt, nil+}++func convertSetOperation(t pgquery.SetOperation) (ast.SetOperationType, error) {+ switch t {+ case pgquery.SetOperation_SETOP_NONE:+ return ast.SetOperationTypeNone, nil+ case pgquery.SetOperation_SETOP_UNION:+ return ast.SetOperationTypeUnion, nil+ case pgquery.SetOperation_SETOP_INTERSECT:+ return ast.SetOperationTypeIntersect, nil+ case pgquery.SetOperation_SETOP_EXCEPT:+ return ast.SetOperationTypeExcept, nil+ default:+ return 0, fmt.Errorf("failed to parse set operation: unknown type %s", t)+ }+}+func convertListToTableDef(in *pgquery.Node_List) (*ast.TableDef, error) {stringList, err := convertListToStringList(in)if err != nil {diff --git a/plugin/parser/engine/pg/convert_test.go b/plugin/parser/engine/pg/convert_test.goindex ebd3bbe5b2..600af794d0 100644--- a/plugin/parser/engine/pg/convert_test.go+++ b/plugin/parser/engine/pg/convert_test.go@@ -648,3 +648,152 @@ func TestPGNotNullStmt(t *testing.T) {runTests(t, tests)}++func TestPGSelectStmt(t *testing.T) {+ tests := []testData{+ {+ stmt: "SELECT public.t.a, t.*, * FROM t",+ want: []ast.Node{+ &ast.SelectStmt{+ SetOperation: ast.SetOperationTypeNone,+ FieldList: []ast.ExpressionNode{+ &ast.ColumnNameDef{+ Table: &ast.TableDef{+ Schema: "public",+ Name: "t",+ },+ ColumnName: "a",+ },+ &ast.ColumnNameDef{+ Table: &ast.TableDef{Name: "t"},+ ColumnName: "*",+ },+ &ast.ColumnNameDef{+ Table: &ast.TableDef{},+ ColumnName: "*",+ },+ },+ },+ },+ textList: []string{+ "SELECT public.t.a, t.*, * FROM t",+ },+ },+ {+ stmt: `+ SELECT+ public.t.a, b, lower(a), b>a+ FROM+ t+ WHERE+ a > 0+ AND (c not LIKE 'xyz' or true)+ AND b LIKE '%csdbc'+ AND a in+ (SELECT * FROM t1 WHERE x LIKE b)+ UNION+ SELECT * FROM t`,+ want: []ast.Node{+ &ast.SelectStmt{+ SetOperation: ast.SetOperationTypeUnion,+ LQuery: &ast.SelectStmt{+ SetOperation: ast.SetOperationTypeNone,+ FieldList: []ast.ExpressionNode{+ &ast.ColumnNameDef{+ Table: &ast.TableDef{+ Schema: "public",+ Name: "t",+ },+ ColumnName: "a",+ },+ &ast.ColumnNameDef{+ Table: &ast.TableDef{},+ ColumnName: "b",+ },+ &ast.UnconvertedExpressionDef{},+ &ast.UnconvertedExpressionDef{},+ },+ WhereClause: &ast.UnconvertedExpressionDef{},+ PatternLikeList: []*ast.PatternLikeDef{+ {+ Not: true,+ Expression: &ast.ColumnNameDef{+ Table: &ast.TableDef{},+ ColumnName: "c",+ },+ Pattern: &ast.StringDef{Value: "xyz"},+ },+ {+ Expression: &ast.ColumnNameDef{+ Table: &ast.TableDef{},+ ColumnName: "b",+ },+ Pattern: &ast.StringDef{Value: "%csdbc"},+ },+ },+ SubqueryList: []*ast.SubqueryDef{+ {+ Select: &ast.SelectStmt{+ SetOperation: ast.SetOperationTypeNone,+ FieldList: []ast.ExpressionNode{+ &ast.ColumnNameDef{+ Table: &ast.TableDef{},+ ColumnName: "*",+ },+ },+ WhereClause: &ast.PatternLikeDef{+ Expression: &ast.ColumnNameDef{+ Table: &ast.TableDef{},+ ColumnName: "x",+ },+ Pattern: &ast.ColumnNameDef{+ Table: &ast.TableDef{},+ ColumnName: "b",+ },+ },+ PatternLikeList: []*ast.PatternLikeDef{+ {+ Expression: &ast.ColumnNameDef{+ Table: &ast.TableDef{},+ ColumnName: "x",+ },+ Pattern: &ast.ColumnNameDef{+ Table: &ast.TableDef{},+ ColumnName: "b",+ },+ },+ },+ },+ },+ },+ },+ RQuery: &ast.SelectStmt{+ SetOperation: ast.SetOperationTypeNone,+ FieldList: []ast.ExpressionNode{+ &ast.ColumnNameDef{+ Table: &ast.TableDef{},+ ColumnName: "*",+ },+ },+ },+ },+ },+ textList: []string{+ `SELECT+ public.t.a, b, lower(a), b>a+ FROM+ t+ WHERE+ a > 0+ AND (c not LIKE 'xyz' or true)+ AND b LIKE '%csdbc'+ AND a in+ (SELECT * FROM t1 WHERE x LIKE b)+ UNION+ SELECT * FROM t`,+ },+ },+ }++ runTests(t, tests)+}diff --git a/plugin/parser/engine/pg/parser.go b/plugin/parser/engine/pg/parser.goindex b1c106c056..6b3648f37b 100644--- a/plugin/parser/engine/pg/parser.go+++ b/plugin/parser/engine/pg/parser.go@@ -12,6 +12,11 @@ var (_ parser.Parser = (*PostgreSQLParser)(nil))+const (+ operatorLike string = "~~"+ operatorNotLike string = "!~~"+)+func init() {parser.Register(parser.Postgres, &PostgreSQLParser{})}