postgresql-parser icon indicating copy to clipboard operation
postgresql-parser copied to clipboard

无法解析带有类型转换符 "::" 的语句

Open Aaron3S opened this issue 2 years ago • 1 comments

解析此种类型的sql失败:

SELECT COUNT ( * ) FROM pg_class C LEFT JOIN pg_namespace n ON n.oid = C.relnamespace WHERE C.relkind = ANY ( '{r,v,m}' :: CHAR [] ) UNION SELECT COUNT ( * ) FROM pg_attribute A JOIN pg_class C ON A.attrelid = C.oid JOIN pg_namespace n ON C.relnamespace = n.oid JOIN pg_type tp ON tp.typelem = A.atttypid WHERE A.attnum > 0 UNION SELECT COUNT ( * ) FROM information_schema.routines

出错的位置在 "::" 操作符

Aaron3S avatar Mar 31 '22 08:03 Aaron3S

It okay in my test:

package main

import (
	"fmt"
	"log"

	"github.com/auxten/postgresql-parser/pkg/sql/parser"
	"github.com/auxten/postgresql-parser/pkg/sql/sem/tree"
)

func main() {
	sql := `
SELECT COUNT
( * )
FROM
pg_class
C LEFT JOIN pg_namespace n ON n.oid = C.relnamespace
WHERE
C.relkind = ANY ( '{r,v,m}' :: CHAR [] ) UNION
SELECT COUNT
( * )
FROM
pg_attribute
A JOIN pg_class C ON A.attrelid = C.oid
JOIN pg_namespace n ON C.relnamespace = n.oid
JOIN pg_type tp ON tp.typelem = A.atttypid
WHERE
A.attnum > 0 UNION
SELECT COUNT
( * )
FROM
information_schema.routines`

	if stmts, err := parser.Parse(sql); err != nil {
		log.Fatal(err)
	} else {
		for _, stmt := range stmts {
			fmt.Printf("Pretty SQL:\n%s", tree.Pretty(stmt.AST))
		}
	}

}
Pretty SQL:
SELECT
        count(*)
FROM
        pg_class AS c
        LEFT JOIN pg_namespace AS n ON n.oid = c.relnamespace
WHERE
        c.relkind = ANY '{r,v,m}'::CHAR[]
UNION
        SELECT
                count(*)
        FROM
                pg_attribute AS a
                JOIN pg_class AS c ON a.attrelid = c.oid
                JOIN pg_namespace AS n ON c.relnamespace = n.oid
                JOIN pg_type AS tp ON tp.typelem = a.atttypid
        WHERE
                a.attnum > 0
UNION SELECT count(*) FROM information_schema.routines

auxten avatar Apr 22 '22 07:04 auxten