Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: add ANTLR-based statement type detection for PostgreSQL (#17890)

h3n4l0c844f92e682
diff --git a/backend/plugin/parser/pg/statement_type_antlr.go b/backend/plugin/parser/pg/statement_type_antlr.go
new file mode 100644
index 0000000000..2c60006749
--- /dev/null
+++ b/backend/plugin/parser/pg/statement_type_antlr.go
@@ -0,0 +1,602 @@
+package pg
+
+import (
+ "github.com/antlr4-go/antlr/v4"
+ parser "github.com/bytebase/parser/postgresql"
+ "github.com/pkg/errors"
+)
+
+// GetStatementTypesANTLR returns statement types from ANTLR parse result.
+func GetStatementTypesANTLR(parseResult *ParseResult) ([]string, error) {
+ if parseResult == nil || parseResult.Tree == nil {
+ return nil, errors.New("invalid parse result")
+ }
+
+ collector := &statementTypeCollector{
+ types: make(map[string]bool),
+ }
+
+ antlr.ParseTreeWalkerDefault.Walk(collector, parseResult.Tree)
+
+ var sqlTypes []string
+ for sqlType := range collector.types {
+ sqlTypes = append(sqlTypes, sqlType)
+ }
+ return sqlTypes, nil
+}
+
+// GetStatementTypesWithPositionsANTLR returns statement types with position information from ANTLR parse result.
+func GetStatementTypesWithPositionsANTLR(parseResult *ParseResult) ([]StatementTypeWithPosition, error) {
+ if parseResult == nil || parseResult.Tree == nil {
+ return nil, errors.New("invalid parse result")
+ }
+
+ collector := &statementTypeCollectorWithPosition{
+ tokens: parseResult.Tokens,
+ }
+
+ antlr.ParseTreeWalkerDefault.Walk(collector, parseResult.Tree)
+
+ return collector.results, nil
+}
+
+// statementTypeCollector collects unique statement types.
+type statementTypeCollector struct {
+ *parser.BasePostgreSQLParserListener
+ types map[string]bool
+}
+
+// statementTypeCollectorWithPosition collects statement types with positions.
+type statementTypeCollectorWithPosition struct {
+ *parser.BasePostgreSQLParserListener
+ tokens *antlr.CommonTokenStream
+ results []StatementTypeWithPosition
+}
+
+// Helper function to add statement type.
+func (c *statementTypeCollector) addType(stmtType string) {
+ if stmtType != "" && stmtType != "UNKNOWN" {
+ c.types[stmtType] = true
+ }
+}
+
+// Helper function to add statement with position.
+func (c *statementTypeCollectorWithPosition) addStatement(stmtType string, ctx antlr.ParserRuleContext) {
+ if stmtType == "" || stmtType == "UNKNOWN" {
+ return
+ }
+
+ // Get line number from the stop token
+ line := 0
+ if ctx.GetStop() != nil {
+ line = ctx.GetStop().GetLine()
+ }
+
+ // Get statement text
+ text := ""
+ if c.tokens != nil && ctx.GetStart() != nil && ctx.GetStop() != nil {
+ text = c.tokens.GetTextFromInterval(antlr.NewInterval(
+ ctx.GetStart().GetTokenIndex(),
+ ctx.GetStop().GetTokenIndex(),
+ ))
+ }
+
+ c.results = append(c.results, StatementTypeWithPosition{
+ Type: stmtType,
+ Line: line,
+ Text: text,
+ })
+}
+
+// CREATE TABLE statements
+func (c *statementTypeCollector) EnterCreatestmt(ctx *parser.CreatestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("CREATE_TABLE")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterCreatestmt(ctx *parser.CreatestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("CREATE_TABLE", ctx)
+}
+
+// CREATE VIEW statements
+func (c *statementTypeCollector) EnterViewstmt(ctx *parser.ViewstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("CREATE_VIEW")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterViewstmt(ctx *parser.ViewstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("CREATE_VIEW", ctx)
+}
+
+// CREATE INDEX statements
+func (c *statementTypeCollector) EnterIndexstmt(ctx *parser.IndexstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("CREATE_INDEX")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterIndexstmt(ctx *parser.IndexstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("CREATE_INDEX", ctx)
+}
+
+// CREATE SEQUENCE statements
+func (c *statementTypeCollector) EnterCreateseqstmt(ctx *parser.CreateseqstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("CREATE_SEQUENCE")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterCreateseqstmt(ctx *parser.CreateseqstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("CREATE_SEQUENCE", ctx)
+}
+
+// CREATE SCHEMA statements
+func (c *statementTypeCollector) EnterCreateschemastmt(ctx *parser.CreateschemastmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("CREATE_SCHEMA")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterCreateschemastmt(ctx *parser.CreateschemastmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("CREATE_SCHEMA", ctx)
+}
+
+// CREATE FUNCTION statements
+func (c *statementTypeCollector) EnterCreatefunctionstmt(ctx *parser.CreatefunctionstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("CREATE_FUNCTION")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterCreatefunctionstmt(ctx *parser.CreatefunctionstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("CREATE_FUNCTION", ctx)
+}
+
+// CREATE TRIGGER statements
+func (c *statementTypeCollector) EnterCreatetrigstmt(ctx *parser.CreatetrigstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("CREATE_TRIGGER")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterCreatetrigstmt(ctx *parser.CreatetrigstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("CREATE_TRIGGER", ctx)
+}
+
+// CREATE EXTENSION statements
+func (c *statementTypeCollector) EnterCreateextensionstmt(ctx *parser.CreateextensionstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("CREATE_EXTENSION")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterCreateextensionstmt(ctx *parser.CreateextensionstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("CREATE_EXTENSION", ctx)
+}
+
+// CREATE DATABASE statements
+func (c *statementTypeCollector) EnterCreatedbstmt(ctx *parser.CreatedbstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("CREATE_DATABASE")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterCreatedbstmt(ctx *parser.CreatedbstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("CREATE_DATABASE", ctx)
+}
+
+// DROP statements
+func (c *statementTypeCollector) EnterDropstmt(ctx *parser.DropstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType(getDropStatementType(ctx))
+}
+
+func (c *statementTypeCollectorWithPosition) EnterDropstmt(ctx *parser.DropstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement(getDropStatementType(ctx), ctx)
+}
+
+// ALTER statements
+func (c *statementTypeCollector) EnterAltertablestmt(ctx *parser.AltertablestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+
+ // Check if this is ALTER VIEW
+ if ctx.VIEW() != nil {
+ c.addType("ALTER_VIEW")
+ return
+ }
+
+ // Parse ALTER TABLE sub-operations if alter_table_cmds exists
+ if cmds := ctx.Alter_table_cmds(); cmds != nil {
+ for _, cmd := range cmds.AllAlter_table_cmd() {
+ stmtType := getAlterTableCmdType(cmd)
+ c.addType(stmtType)
+ }
+ } else {
+ // Fallback to generic ALTER_TABLE if no cmds
+ c.addType("ALTER_TABLE")
+ }
+}
+
+func (c *statementTypeCollectorWithPosition) EnterAltertablestmt(ctx *parser.AltertablestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+
+ // Check if this is ALTER VIEW
+ if ctx.VIEW() != nil {
+ c.addStatement("ALTER_VIEW", ctx)
+ return
+ }
+
+ // Parse ALTER TABLE sub-operations if alter_table_cmds exists
+ if cmds := ctx.Alter_table_cmds(); cmds != nil {
+ for _, cmd := range cmds.AllAlter_table_cmd() {
+ stmtType := getAlterTableCmdType(cmd)
+ c.addStatement(stmtType, ctx)
+ }
+ } else {
+ // Fallback to generic ALTER_TABLE if no cmds
+ c.addStatement("ALTER_TABLE", ctx)
+ }
+}
+
+func (c *statementTypeCollector) EnterAlterseqstmt(ctx *parser.AlterseqstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("ALTER_SEQUENCE")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterAlterseqstmt(ctx *parser.AlterseqstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("ALTER_SEQUENCE", ctx)
+}
+
+func (c *statementTypeCollector) EnterAlterenumstmt(ctx *parser.AlterenumstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("ALTER_TYPE")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterAlterenumstmt(ctx *parser.AlterenumstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("ALTER_TYPE", ctx)
+}
+
+// RENAME statements
+func (c *statementTypeCollector) EnterRenamestmt(ctx *parser.RenamestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType(getRenameStatementType(ctx))
+}
+
+func (c *statementTypeCollectorWithPosition) EnterRenamestmt(ctx *parser.RenamestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement(getRenameStatementType(ctx), ctx)
+}
+
+// COMMENT statements
+func (c *statementTypeCollector) EnterCommentstmt(ctx *parser.CommentstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("COMMENT")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterCommentstmt(ctx *parser.CommentstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("COMMENT", ctx)
+}
+
+// CREATE TYPE statements
+func (c *statementTypeCollector) EnterDefinestmt(ctx *parser.DefinestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ // Check if this is CREATE TYPE
+ if ctx.TYPE_P() != nil {
+ c.addType("CREATE_TYPE")
+ }
+}
+
+func (c *statementTypeCollectorWithPosition) EnterDefinestmt(ctx *parser.DefinestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ // Check if this is CREATE TYPE
+ if ctx.TYPE_P() != nil {
+ c.addStatement("CREATE_TYPE", ctx)
+ }
+}
+
+// DROP FUNCTION statements
+func (c *statementTypeCollector) EnterRemovefuncstmt(ctx *parser.RemovefuncstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("DROP_FUNCTION")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterRemovefuncstmt(ctx *parser.RemovefuncstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("DROP_FUNCTION", ctx)
+}
+
+// DROP DATABASE statements
+func (c *statementTypeCollector) EnterDropdbstmt(ctx *parser.DropdbstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("DROP_DATABASE")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterDropdbstmt(ctx *parser.DropdbstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("DROP_DATABASE", ctx)
+}
+
+// DML statements
+func (c *statementTypeCollector) EnterInsertstmt(ctx *parser.InsertstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("INSERT")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterInsertstmt(ctx *parser.InsertstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("INSERT", ctx)
+}
+
+func (c *statementTypeCollector) EnterUpdatestmt(ctx *parser.UpdatestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("UPDATE")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterUpdatestmt(ctx *parser.UpdatestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("UPDATE", ctx)
+}
+
+func (c *statementTypeCollector) EnterDeletestmt(ctx *parser.DeletestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addType("DELETE")
+}
+
+func (c *statementTypeCollectorWithPosition) EnterDeletestmt(ctx *parser.DeletestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+ c.addStatement("DELETE", ctx)
+}
+
+// getDropStatementType determines the specific DROP statement type.
+func getDropStatementType(ctx *parser.DropstmtContext) string {
+ if ctx == nil {
+ return ""
+ }
+
+ // Check TYPE_P for DROP TYPE
+ if ctx.TYPE_P() != nil {
+ return "DROP_TYPE"
+ }
+
+ // Check DOMAIN_P for DROP DOMAIN (not in legacy, return UNKNOWN)
+ if ctx.DOMAIN_P() != nil {
+ return "UNKNOWN"
+ }
+
+ // Check object_type_any_name (TABLE, SEQUENCE, VIEW, INDEX, etc.)
+ if ctx.Object_type_any_name() != nil {
+ objType := ctx.Object_type_any_name()
+ if objType.TABLE() != nil {
+ return "DROP_TABLE"
+ }
+ if objType.VIEW() != nil {
+ // Check if MATERIALIZED VIEW or regular VIEW
+ // Both treated as DROP_TABLE in legacy
+ return "DROP_TABLE"
+ }
+ if objType.INDEX() != nil {
+ return "DROP_INDEX"
+ }
+ if objType.SEQUENCE() != nil {
+ return "DROP_SEQUENCE"
+ }
+ // Other types like COLLATION, CONVERSION, STATISTICS not in legacy
+ return "UNKNOWN"
+ }
+
+ // Check drop_type_name (SCHEMA, EXTENSION, etc.)
+ if ctx.Drop_type_name() != nil {
+ dropType := ctx.Drop_type_name()
+ if dropType.SCHEMA() != nil {
+ return "DROP_SCHEMA"
+ }
+ if dropType.EXTENSION() != nil {
+ return "DROP_EXTENSION"
+ }
+ // Other types like ACCESS METHOD, EVENT TRIGGER, PUBLICATION not in legacy
+ return "UNKNOWN"
+ }
+
+ // Check object_type_name_on_any_name (TRIGGER, RULE, POLICY with "ON table" syntax)
+ if ctx.Object_type_name_on_any_name() != nil {
+ objTypeOn := ctx.Object_type_name_on_any_name()
+ if objTypeOn.TRIGGER() != nil {
+ return "DROP_TRIGGER"
+ }
+ // RULE and POLICY not in legacy
+ return "UNKNOWN"
+ }
+
+ // Default for unhandled cases
+ return "UNKNOWN"
+}
+
+// getAlterTableCmdType determines the specific ALTER TABLE sub-operation type.
+func getAlterTableCmdType(cmd parser.IAlter_table_cmdContext) string {
+ if cmd == nil {
+ return "ALTER_TABLE"
+ }
+
+ // ADD COLUMN
+ if cmd.ADD_P() != nil && cmd.ColumnDef() != nil {
+ return "ALTER_TABLE_ADD_COLUMN_LIST"
+ }
+
+ // ADD CONSTRAINT
+ if cmd.ADD_P() != nil && cmd.Tableconstraint() != nil {
+ return "ALTER_TABLE_ADD_CONSTRAINT"
+ }
+
+ // ALTER COLUMN operations (check these BEFORE DROP to avoid conflicts)
+ if cmd.ALTER() != nil && len(cmd.AllColid()) > 0 {
+ // ALTER COLUMN ... TYPE
+ if cmd.TYPE_P() != nil {
+ return "ALTER_COLUMN_TYPE"
+ }
+
+ // ALTER COLUMN ... DROP NOT NULL
+ if cmd.DROP() != nil && cmd.NOT() != nil && cmd.NULL_P() != nil {
+ return "DROP_NOT_NULL"
+ }
+
+ // ALTER COLUMN ... DROP DEFAULT
+ if cmd.Alter_column_default() != nil {
+ alterDefault := cmd.Alter_column_default()
+ // Check if it's DROP DEFAULT (not SET DEFAULT)
+ if alterDefault.DROP() != nil {
+ return "DROP_DEFAULT"
+ }
+ }
+ }
+
+ // DROP COLUMN (must be after ALTER COLUMN checks)
+ if cmd.DROP() != nil && len(cmd.AllColid()) > 0 && cmd.CONSTRAINT() == nil {
+ return "DROP_COLUMN"
+ }
+
+ // DROP CONSTRAINT
+ if cmd.DROP() != nil && cmd.CONSTRAINT() != nil {
+ return "DROP_CONSTRAINT"
+ }
+
+ // Default to ALTER_TABLE for other operations
+ return "ALTER_TABLE"
+}
+
+// getRenameStatementType determines the specific RENAME statement type.
+func getRenameStatementType(ctx *parser.RenamestmtContext) string {
+ if ctx == nil {
+ return ""
+ }
+
+ // Check for ALTER TABLE variants
+ if ctx.TABLE() != nil {
+ // ALTER TABLE ... RENAME CONSTRAINT ... TO ...
+ if ctx.CONSTRAINT() != nil {
+ return "RENAME_CONSTRAINT"
+ }
+ // ALTER TABLE ... RENAME [COLUMN] ... TO ...
+ // RENAME_COLUMN has 2 name elements (old_name, new_name)
+ // RENAME_TABLE has 1 name element (new_table_name)
+ // The table name is in relation_expr, not counted in AllName()
+ if ctx.Opt_column() != nil || len(ctx.AllName()) >= 2 {
+ return "RENAME_COLUMN"
+ }
+ // ALTER TABLE ... RENAME TO ...
+ return "RENAME_TABLE"
+ }
+
+ // Check for ALTER INDEX
+ if ctx.INDEX() != nil {
+ return "RENAME_INDEX"
+ }
+
+ // Check for ALTER SCHEMA
+ if ctx.SCHEMA() != nil {
+ return "RENAME_SCHEMA"
+ }
+
+ // Check for ALTER SEQUENCE
+ if ctx.SEQUENCE() != nil {
+ return "RENAME_SEQUENCE"
+ }
+
+ // Check for ALTER VIEW (includes MATERIALIZED VIEW)
+ if ctx.VIEW() != nil {
+ return "RENAME_VIEW"
+ }
+
+ // Default for other RENAME types (AGGREGATE, COLLATION, DOMAIN, FUNCTION, etc.)
+ // Return UNKNOWN to maintain backward compatibility
+ return "UNKNOWN"
+}
diff --git a/backend/plugin/parser/pg/statement_type_antlr_test.go b/backend/plugin/parser/pg/statement_type_antlr_test.go
new file mode 100644
index 0000000000..778a7c2594
--- /dev/null
+++ b/backend/plugin/parser/pg/statement_type_antlr_test.go
@@ -0,0 +1,289 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestGetStatementTypesANTLR(t *testing.T) {
+ tests := []struct {
+ name string
+ sql string
+ expectedTypes []string
+ }{
+ {
+ name: "CREATE TABLE",
+ sql: "CREATE TABLE t1 (id INT);",
+ expectedTypes: []string{"CREATE_TABLE"},
+ },
+ {
+ name: "CREATE VIEW",
+ sql: "CREATE VIEW v1 AS SELECT * FROM t1;",
+ expectedTypes: []string{"CREATE_VIEW"},
+ },
+ {
+ name: "CREATE INDEX",
+ sql: "CREATE INDEX idx_name ON t1(name);",
+ expectedTypes: []string{"CREATE_INDEX"},
+ },
+ {
+ name: "CREATE SEQUENCE",
+ sql: "CREATE SEQUENCE seq1;",
+ expectedTypes: []string{"CREATE_SEQUENCE"},
+ },
+ {
+ name: "CREATE SCHEMA",
+ sql: "CREATE SCHEMA schema1;",
+ expectedTypes: []string{"CREATE_SCHEMA"},
+ },
+ {
+ name: "CREATE FUNCTION",
+ sql: "CREATE FUNCTION func1() RETURNS INT AS $$ BEGIN RETURN 1; END; $$ LANGUAGE plpgsql;",
+ expectedTypes: []string{"CREATE_FUNCTION"},
+ },
+ {
+ name: "DROP TABLE",
+ sql: "DROP TABLE t1;",
+ expectedTypes: []string{"DROP_TABLE"},
+ },
+ {
+ name: "DROP INDEX",
+ sql: "DROP INDEX idx_name;",
+ expectedTypes: []string{"DROP_INDEX"},
+ },
+ {
+ name: "DROP SCHEMA",
+ sql: "DROP SCHEMA schema1;",
+ expectedTypes: []string{"DROP_SCHEMA"},
+ },
+ {
+ name: "DROP SEQUENCE",
+ sql: "DROP SEQUENCE seq1;",
+ expectedTypes: []string{"DROP_SEQUENCE"},
+ },
+ {
+ name: "DROP EXTENSION",
+ sql: "DROP EXTENSION postgis;",
+ expectedTypes: []string{"DROP_EXTENSION"},
+ },
+ {
+ name: "DROP DATABASE",
+ sql: "DROP DATABASE testdb;",
+ expectedTypes: []string{"DROP_DATABASE"},
+ },
+ {
+ name: "DROP TYPE",
+ sql: "DROP TYPE custom_type;",
+ expectedTypes: []string{"DROP_TYPE"},
+ },
+ {
+ name: "DROP TRIGGER",
+ sql: "DROP TRIGGER trig1 ON t1;",
+ expectedTypes: []string{"DROP_TRIGGER"},
+ },
+ {
+ name: "DROP VIEW",
+ sql: "DROP VIEW v1;",
+ expectedTypes: []string{"DROP_TABLE"},
+ },
+ {
+ name: "DROP FUNCTION",
+ sql: "DROP FUNCTION func1();",
+ expectedTypes: []string{"DROP_FUNCTION"},
+ },
+ {
+ name: "CREATE TYPE",
+ sql: "CREATE TYPE custom_type AS ENUM ('a', 'b', 'c');",
+ expectedTypes: []string{"CREATE_TYPE"},
+ },
+ {
+ name: "ALTER TABLE ADD COLUMN",
+ sql: "ALTER TABLE t1 ADD COLUMN name VARCHAR(100);",
+ expectedTypes: []string{"ALTER_TABLE_ADD_COLUMN_LIST"},
+ },
+ {
+ name: "ALTER TABLE ADD CONSTRAINT",
+ sql: "ALTER TABLE t1 ADD CONSTRAINT pk_id PRIMARY KEY (id);",
+ expectedTypes: []string{"ALTER_TABLE_ADD_CONSTRAINT"},
+ },
+ {
+ name: "ALTER TABLE DROP COLUMN",
+ sql: "ALTER TABLE t1 DROP COLUMN name;",
+ expectedTypes: []string{"DROP_COLUMN"},
+ },
+ {
+ name: "ALTER TABLE DROP CONSTRAINT",
+ sql: "ALTER TABLE t1 DROP CONSTRAINT pk_id;",
+ expectedTypes: []string{"DROP_CONSTRAINT"},
+ },
+ {
+ name: "ALTER TABLE ALTER COLUMN TYPE",
+ sql: "ALTER TABLE t1 ALTER COLUMN name TYPE TEXT;",
+ expectedTypes: []string{"ALTER_COLUMN_TYPE"},
+ },
+ {
+ name: "ALTER TABLE ALTER COLUMN DROP DEFAULT",
+ sql: "ALTER TABLE t1 ALTER COLUMN name DROP DEFAULT;",
+ expectedTypes: []string{"DROP_DEFAULT"},
+ },
+ {
+ name: "ALTER TABLE ALTER COLUMN DROP NOT NULL",
+ sql: "ALTER TABLE t1 ALTER COLUMN name DROP NOT NULL;",
+ expectedTypes: []string{"DROP_NOT_NULL"},
+ },
+ {
+ name: "ALTER VIEW",
+ sql: "ALTER VIEW v1 OWNER TO user1;",
+ expectedTypes: []string{"ALTER_VIEW"},
+ },
+ {
+ name: "ALTER TABLE (generic)",
+ sql: "ALTER TABLE t1 ENABLE ROW LEVEL SECURITY;",
+ expectedTypes: []string{"ALTER_TABLE"},
+ },
+ {
+ name: "ALTER SEQUENCE",
+ sql: "ALTER SEQUENCE seq1 RESTART WITH 100;",
+ expectedTypes: []string{"ALTER_SEQUENCE"},
+ },
+ {
+ name: "INSERT",
+ sql: "INSERT INTO t1 (id) VALUES (1);",
+ expectedTypes: []string{"INSERT"},
+ },
+ {
+ name: "UPDATE",
+ sql: "UPDATE t1 SET name = 'test' WHERE id = 1;",
+ expectedTypes: []string{"UPDATE"},
+ },
+ {
+ name: "DELETE",
+ sql: "DELETE FROM t1 WHERE id = 1;",
+ expectedTypes: []string{"DELETE"},
+ },
+ {
+ name: "COMMENT",
+ sql: "COMMENT ON TABLE t1 IS 'test table';",
+ expectedTypes: []string{"COMMENT"},
+ },
+ {
+ name: "Multiple statements",
+ sql: `CREATE TABLE t1 (id INT);
+ CREATE INDEX idx_id ON t1(id);
+ INSERT INTO t1 (id) VALUES (1);`,
+ expectedTypes: []string{"CREATE_TABLE", "CREATE_INDEX", "INSERT"},
+ },
+ {
+ name: "RENAME TABLE",
+ sql: "ALTER TABLE t1 RENAME TO t2;",
+ expectedTypes: []string{"RENAME_TABLE"},
+ },
+ {
+ name: "RENAME COLUMN",
+ sql: "ALTER TABLE t1 RENAME COLUMN old_name TO new_name;",
+ expectedTypes: []string{"RENAME_COLUMN"},
+ },
+ {
+ name: "RENAME COLUMN without COLUMN keyword",
+ sql: "ALTER TABLE t1 RENAME old_name TO new_name;",
+ expectedTypes: []string{"RENAME_COLUMN"},
+ },
+ {
+ name: "RENAME CONSTRAINT",
+ sql: "ALTER TABLE t1 RENAME CONSTRAINT old_constraint TO new_constraint;",
+ expectedTypes: []string{"RENAME_CONSTRAINT"},
+ },
+ {
+ name: "RENAME INDEX",
+ sql: "ALTER INDEX idx_old RENAME TO idx_new;",
+ expectedTypes: []string{"RENAME_INDEX"},
+ },
+ {
+ name: "RENAME SCHEMA",
+ sql: "ALTER SCHEMA old_schema RENAME TO new_schema;",
+ expectedTypes: []string{"RENAME_SCHEMA"},
+ },
+ {
+ name: "RENAME SEQUENCE",
+ sql: "ALTER SEQUENCE seq_old RENAME TO seq_new;",
+ expectedTypes: []string{"RENAME_SEQUENCE"},
+ },
+ {
+ name: "RENAME VIEW",
+ sql: "ALTER VIEW v_old RENAME TO v_new;",
+ expectedTypes: []string{"RENAME_VIEW"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ parseResult, err := ParsePostgreSQL(tt.sql)
+ require.NoError(t, err)
+
+ types, err := GetStatementTypesANTLR(parseResult)
+ require.NoError(t, err)
+ require.ElementsMatch(t, tt.expectedTypes, types)
+ })
+ }
+}
+
+func TestGetStatementTypesWithPositionsANTLR(t *testing.T) {
+ tests := []struct {
+ name string
+ sql string
+ expected []StatementTypeWithPosition
+ }{
+ {
+ name: "Single statement",
+ sql: "CREATE TABLE t1 (id INT);",
+ expected: []StatementTypeWithPosition{
+ {
+ Type: "CREATE_TABLE",
+ Line: 1,
+ Text: "CREATE TABLE t1 (id INT);",
+ },
+ },
+ },
+ {
+ name: "Multiple statements",
+ sql: `CREATE TABLE t1 (id INT);
+DROP TABLE t2;
+INSERT INTO t1 VALUES (1);`,
+ expected: []StatementTypeWithPosition{
+ {
+ Type: "CREATE_TABLE",
+ Line: 1,
+ },
+ {
+ Type: "DROP_TABLE",
+ Line: 2,
+ },
+ {
+ Type: "INSERT",
+ Line: 3,
+ },
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ parseResult, err := ParsePostgreSQL(tt.sql)
+ require.NoError(t, err)
+
+ results, err := GetStatementTypesWithPositionsANTLR(parseResult)
+ require.NoError(t, err)
+ require.Len(t, results, len(tt.expected))
+
+ for i, expected := range tt.expected {
+ require.Equal(t, expected.Type, results[i].Type, "Statement %d type mismatch", i)
+ require.Equal(t, expected.Line, results[i].Line, "Statement %d line mismatch", i)
+ if expected.Text != "" {
+ // Check that text contains expected content (may not include semicolon)
+ require.Contains(t, results[i].Text, "CREATE TABLE t1", "Statement %d text mismatch", i)
+ }
+ }
+ })
+ }
+}