@@ -61,7 +61,14 @@ function isPlpgsqlFunction(stmt: any): boolean {
6161 return language === 'plpgsql' ;
6262}
6363
64- function extractFunctionInfo ( stmt : any , stmtIndex : number , fullSql : string ) : ParsedFunction | null {
64+ function getStatementSql ( sqlBuffer : Buffer , rawStmt : any ) : string {
65+ const start = rawStmt ?. stmt_location ?? 0 ;
66+ const len = rawStmt ?. stmt_len ;
67+ const end = len !== undefined ? start + len : sqlBuffer . length ;
68+ return sqlBuffer . slice ( start , end ) . toString ( 'utf8' ) ;
69+ }
70+
71+ function extractFunctionInfo ( stmt : any , stmtIndex : number , stmtSql : string ) : ParsedFunction | null {
6572 const createFunctionStmt = stmt ?. CreateFunctionStmt ;
6673 if ( ! createFunctionStmt ) return null ;
6774
@@ -72,7 +79,10 @@ function extractFunctionInfo(stmt: any, stmtIndex: number, fullSql: string): Par
7279 if ( ! body ) return null ;
7380
7481 try {
75- const plpgsqlRaw = parsePlPgSQLSync ( fullSql ) as unknown as PLpgSQLParseResult ;
82+ // Parse only this statement's SQL. Parsing the full script would return
83+ // every function's PL/pgSQL AST in plpgsql_funcs, and downstream deparse
84+ // pairs each statement with plpgsql_funcs[0].
85+ const plpgsqlRaw = parsePlPgSQLSync ( stmtSql ) as unknown as PLpgSQLParseResult ;
7686 const { ast : hydrated , stats, errors } = hydratePlpgsqlAst ( plpgsqlRaw ) ;
7787
7888 return {
@@ -99,14 +109,15 @@ export function parse(sql: string, options: ParseOptions = {}): ParsedScript {
99109 const sqlResult : ParseResult = parseSqlSync ( sql ) ;
100110 const items : ParsedItem [ ] = [ ] ;
101111 const functions : ParsedFunction [ ] = [ ] ;
112+ const sqlBuffer = Buffer . from ( sql , 'utf8' ) ;
102113
103114 if ( sqlResult . stmts ) {
104115 for ( let i = 0 ; i < sqlResult . stmts . length ; i ++ ) {
105116 const rawStmt = sqlResult . stmts [ i ] ;
106117 const stmt = rawStmt ?. stmt ;
107118
108119 if ( stmt && isPlpgsqlFunction ( stmt ) && hydrate ) {
109- const fnInfo = extractFunctionInfo ( stmt , i , sql ) ;
120+ const fnInfo = extractFunctionInfo ( stmt , i , getStatementSql ( sqlBuffer , rawStmt ) ) ;
110121 if ( fnInfo ) {
111122 items . push ( fnInfo ) ;
112123 functions . push ( fnInfo ) ;
0 commit comments