@@ -342,8 +342,11 @@ export class PLpgSQLDeparser {
342342 const localVars = datums . filter ( datum => {
343343 if ( 'PLpgSQL_var' in datum ) {
344344 const v = datum . PLpgSQL_var ;
345- // Skip internal variables
346- if ( v . refname === 'found' || v . refname . startsWith ( '__' ) ) {
345+ // Skip internal variables:
346+ // - 'found' is the implicit FOUND variable
347+ // - 'sqlstate' and 'sqlerrm' are implicit exception handling variables
348+ // - variables starting with '__' are internal
349+ if ( v . refname === 'found' || v . refname === 'sqlstate' || v . refname === 'sqlerrm' || v . refname . startsWith ( '__' ) ) {
347350 return false ;
348351 }
349352 // Skip variables without lineno (usually parameters or internal)
@@ -457,8 +460,13 @@ export class PLpgSQLDeparser {
457460 private deparseType ( typeNode : PLpgSQLTypeNode ) : string {
458461 if ( 'PLpgSQL_type' in typeNode ) {
459462 let typname = typeNode . PLpgSQL_type . typname ;
460- // Clean up type names (remove pg_catalog prefix and quotes)
461- typname = typname . replace ( / ^ p g _ c a t a l o g \. / , '' ) . replace ( / " / g, '' ) ;
463+ // Remove quotes
464+ typname = typname . replace ( / " / g, '' ) ;
465+ // Strip pg_catalog. prefix for built-in types, but preserve schema qualification
466+ // for %rowtype and %type references where the schema is part of the table/variable reference
467+ if ( ! typname . includes ( '%rowtype' ) && ! typname . includes ( '%type' ) ) {
468+ typname = typname . replace ( / ^ p g _ c a t a l o g \. / , '' ) ;
469+ }
462470 return typname . trim ( ) ;
463471 }
464472 return '' ;
@@ -567,12 +575,17 @@ export class PLpgSQLDeparser {
567575 }
568576
569577 // Exception handlers
570- if ( block . exceptions ?. exc_list ) {
578+ // The exceptions property can be either:
579+ // - { exc_list: [...] } (direct)
580+ // - { PLpgSQL_exception_block: { exc_list: [...] } } (wrapped)
581+ const excList = block . exceptions ?. exc_list ||
582+ ( block . exceptions as any ) ?. PLpgSQL_exception_block ?. exc_list ;
583+ if ( excList ) {
571584 parts . push ( kw ( 'EXCEPTION' ) ) ;
572- for ( const exc of block . exceptions . exc_list ) {
585+ for ( const exc of excList ) {
573586 if ( 'PLpgSQL_exception' in exc ) {
574587 const excData = exc . PLpgSQL_exception ;
575- const conditions = excData . conditions ?. map ( c => {
588+ const conditions = excData . conditions ?. map ( ( c : any ) => {
576589 if ( 'PLpgSQL_condition' in c ) {
577590 return c . PLpgSQL_condition . condname || c . PLpgSQL_condition . sqlerrstate || 'OTHERS' ;
578591 }
0 commit comments