Skip to content
← Blog
pl/sqlplpgsqloracle packagespostgresqlora2pgdatabase migration

Converting Oracle PL/SQL Packages, Triggers and Cursors to PostgreSQL

Brice Ayres /

Short answer

Ora2Pg or AWS DMS Schema Conversion will get you a first draft of a PL/SQL package in PL/pgSQL, but PostgreSQL has no packages, no package-level variables, and no PRAGMA AUTONOMOUS_TRANSACTION. Convert package state, autonomous transactions, SQLCODE-based exception handlers, explicit cursors and Oracle-style triggers against the official porting notes, then prove each routine against the Oracle results before you trust cutover.

Two dark monitors showing an Oracle PL/SQL package beside its PostgreSQL conversion, with official Oracle and PostgreSQL logos

Ora2Pg or AWS DMS Schema Conversion will get you a first draft of a PL/SQL package in PL/pgSQL, but PostgreSQL has no packages, no package-level variables, and no PRAGMA AUTONOMOUS_TRANSACTION — so package state, autonomous transactions, exception handlers that branch on SQLCODE, explicit cursors and Oracle-style triggers are the work that remains. Convert those pieces against the official porting notes, then prove each routine against the Oracle results before you trust the cutover.

This is not a general Oracle-to-PostgreSQL migration plan. For the sequence from assessment through a reversible cutover, see our step-by-step guide. For tool choice, see Ora2Pg versus DMS Schema Conversion. For cost and timing, see the migration cost post. Here we stay on the code those posts flag and leave open: packages, triggers and cursors.

What actually breaks when you convert a PL/SQL package to PL/pgSQL?

The PostgreSQL porting chapter is blunt. Instead of packages, use schemas to group functions. Because there are no packages, there are no package-level variables either; the documented stand-in for per-session state is a temporary table. Several smaller differences sit next to that gap and will break a mechanical rewrite:

  • Function bodies are string literals, so you need dollar quoting (or escaped quotes), RETURNS in the header instead of RETURN, and a LANGUAGE plpgsql clause.
  • Type names need translation: varchar2 becomes varchar or text; number becomes numeric, or a tighter type where that is safe.
  • If a name in an SQL command could be a column or a PL/pgSQL variable, PostgreSQL raises an ambiguity error by default. PL/SQL treats it as a column. You can set plpgsql.variable_conflict to use_column to match Oracle, but it is better to rename the variable.
  • Integer FOR loops with REVERSE count down from the first bound to the second in PL/pgSQL, and from the second to the first in PL/SQL. Swap the bounds when you port, or the loop is empty.
  • FOR loops over queries (other than cursors) require a declared target record or row type. PL/SQL declares that target implicitly.

Ora2Pg’s default is to emulate a package as a schema (PACKAGE_AS_SCHEMA). That gets the call syntax (package.function()) into a shape PostgreSQL can run. It does not recreate package state.

How do you replace package state and initialization?

In Oracle, the values of the variables, constants and cursors a package declares in its specification or body are its package state. If the package declares at least one of those, it is stateful. Each session that references the package gets its own instantiation, and that state persists for the life of the session unless the package is SERIALLY_REUSABLE or the body is recompiled. The package body can also have an initialization section that runs once per session, on first use.

None of that exists in PostgreSQL. A schema of functions is stateless between calls. The official porting advice is to keep per-session state in a temporary table. A typical pattern:

  • Create a TEMP table with ON COMMIT PRESERVE ROWS (or DELETE ROWS, if each transaction should start clean).
  • Replace package variables with a single row, or a key-value row per variable, in that table.
  • Replace package-level cursors with a refcursor you open when you need it, not with a cursor that lives in the schema.
  • Replace the package initialization section with an init function that you call on first use, or that the application calls when the session starts.

If two functions in the old package read and write the same g_rate variable, both of the new functions have to go through the temp table (or through a setter and getter that does). A converted function that compiles but ignores that shared state is a silent behavior change, not a successful port.

How do you replace autonomous transactions?

An Oracle autonomous transaction is an independent transaction started by another one. It can commit or roll back without committing or rolling back the main transaction, so an audit row can survive even when the caller rolls back. You mark a subprogram or a noncompound trigger with PRAGMA AUTONOMOUS_TRANSACTION. You cannot mark a whole package.

PostgreSQL has no such pragma. A COMMIT or ROLLBACK inside a procedure invoked by CALL, or inside a DO block, ends the current transaction and starts a new one. That is useful, and it is not an autonomous transaction: it does not leave the caller’s work open while a side transaction commits.

The usual stand-in is a second connection, so the audit work can commit on that connection while the caller’s transaction is still open. Ora2Pg can translate autonomous transactions into wrapper functions that use dblink or the pg_background extension. dblink is a contrib module that opens a connection to another PostgreSQL database — including back to the same database — and runs commands there. Review those wrappers: a self-connection needs a reachable URI and credentials, and it has different locking and visibility than a pragma. Ora2Pg also leaves COMMIT and ROLLBACK in place by default so you have to read the transaction logic, rather than silently dropping it.

How do exception handlers and SQLCODE map?

In an Oracle exception handler, SQLCODE returns the numeric code of the exception being handled, and 0 outside a handler. For most internally defined exceptions that number is the (negative) Oracle error; NO_DATA_FOUND is +100. SQLERRM returns the message.

In PL/pgSQL you trap errors with a BEGIN ... EXCEPTION WHEN ... THEN block. Conditions are SQLSTATE codes or condition names (unique_violation, WHEN SQLSTATE '23505'), not Oracle error numbers. Inside a handler, the special variables SQLSTATE and SQLERRM are set; GET STACKED DIAGNOSTICS gives you the rest (table, constraint, detail, hint). The special condition OTHERS matches most errors, but not QUERY_CANCELED or ASSERT_FAILURE unless you name them.

Ora2Pg rewrites some of this — dup_val_on_index to unique_violation, SQLCODE to SQLSTATE, raise_application_error to RAISE EXCEPTION. Treat that as a first draft. A handler that branches on SQLCODE = -1 or SQLCODE = +100 is not the same as a handler that inspects a five-character SQLSTATE. Walk those branches against the PostgreSQL error code list and rewrite them by name.

How do cursors change in PL/pgSQL?

Oracle session cursors are either implicit (SQL%FOUND, SQL%NOTFOUND, SQL%ROWCOUNT on the most recent SQL statement) or explicit: you declare, open, fetch and close them, or you use a cursor FOR loop. Package-level cursors are part of package state and persist for the session.

In PL/pgSQL, all cursor access goes through cursor variables of type refcursor. You can declare name CURSOR FOR query, open, fetch and close, or write FOR rec IN query LOOP — and for a query FOR loop, rec must already be declared. The implicit-cursor attributes become FOUND and GET DIAGNOSTICS ... ROW_COUNT. Ora2Pg rewrites many of the notations (SYS_REFCURSOR to REFCURSOR, EXIT WHEN ...%NOTFOUND to IF NOT FOUND THEN EXIT, SQL%NOTFOUND to NOT FOUND). What it cannot invent is a package-level cursor that stays open between function calls; that state has to live in a refcursor you pass, or in a query you run again.

One more trap if you mix cursors with transaction control: in a procedure, a cursor that is part of a FOR loop is converted to a holdable cursor on the first COMMIT or ROLLBACK, and the query is fully evaluated at that point. Locks taken by the cursor’s query are no longer held. That is documented in the transaction chapter, and it will surprise you if you port a loop that commits as it goes.

How do Oracle triggers become PostgreSQL triggers?

An Oracle DML trigger can have the body inline, use :OLD and :NEW, and — for more involved cases — be a compound trigger with statement-level and row-level sections in one object. PostgreSQL splits that into two objects. You write a function that returns trigger (no arguments in the function signature; NEW, OLD and TG_* are supplied as special variables), then a CREATE TRIGGER statement that says when it fires and which function to run.

Other differences that show up in real packages of triggers:

  • There is no compound trigger. Statement-level work that needs to see the whole change set can use transition tables (REFERENCING OLD TABLE / NEW TABLE) on an AFTER trigger, or a second statement-level trigger.
  • A row-level BEFORE trigger can return NULL to skip the operation for that row, or return a modified row. After-row and statement-level return values are ignored.
  • If several triggers of the same kind fire on the same event, PostgreSQL runs them in alphabetical order by trigger name, not in creation order.
  • Audit triggers that used PRAGMA AUTONOMOUS_TRANSACTION need the same second-connection pattern as package subprograms. A COMMIT inside a trigger function is not legal in the usual case, and it would not give you Oracle’s behavior anyway.

Want help converting the hard parts?

We convert PL/SQL packages, triggers and cursors to PL/pgSQL as part of our Oracle to PostgreSQL migration work — including the package-state, autonomous-transaction and exception paths the tools leave, and a regression harness against Oracle. Book a call and we will walk a package through that list with you.

What does Ora2Pg convert, and what do you fix by hand?

When you are migrating from Oracle to PostgreSQL with Ora2Pg, expect a first draft, not finished code. Ora2Pg’s own docs say automatic PL/SQL conversion is a work in progress and you will likely have manual work, especially on function, procedure, package and package-body headers. Export types such as PACKAGE, TRIGGER, FUNCTION and PROCEDURE should be reviewed before you load them. The converter will rewrite a long list of syntax — NVL to coalesce, SYSDATE to LOCALTIMESTAMP, cursor declarations, some exception names — and it will optionally wrap autonomous transactions. It will not invent package state, and it will not prove that a handler still catches the same errors.

AWS DMS Schema Conversion does similar first-draft work when the target is Aurora or RDS PostgreSQL, and flags what it cannot convert. The fuller tool comparison, including what to pick and how to plan a rollback, is in the tools and rollback post. Use this page for the conversion work itself.

How should we test converted packages, triggers and cursors?

Write the tests on the Oracle side first: given this input, this session state and this triggering statement, Oracle returns these results, writes these rows, and raises this exception. Then run the same cases against PostgreSQL. At a minimum, cover:

  • Package state across calls in one session. Set a package variable (or run the init path), call a second function that depends on it, and check the result. Then open a new session and confirm the state does not leak.
  • Autonomous work versus a rollback. Call a routine that writes an audit row and then fails; after the caller rolls back, the audit row should still be there if that was the Oracle behavior.
  • Exception paths. Duplicate keys, NO_DATA_FOUND / SELECT INTO with no row, and any user-defined exceptions the package raises. Compare the SQLSTATE and the message, not just “it threw.”
  • Triggers. A BEFORE row trigger that modifies NEW or skips a row, a statement-level trigger, and any transition-table logic you wrote to replace a compound trigger.
  • Cursors. Row order, empty results, and any loop that commits as it goes.

AI assistants and the conversion tools can produce the first draft faster. The harness is what tells you the package still behaves.

FAQ

Does PostgreSQL have packages?

No. Community PostgreSQL has no package specification, package body, package-level variables or package initialization section. The official guidance is to group functions in a schema and keep per-session state in a temporary table. Ora2Pg’s default PACKAGE_AS_SCHEMA setting follows that for the call syntax only.

Is COMMIT in a PostgreSQL procedure the same as an autonomous transaction?

No. In a procedure called with CALL, or in a DO block, COMMIT ends the current transaction and starts a new one. An Oracle autonomous transaction commits independently of the caller. If you need the audit row to survive a rollback of the main work, use a separate connection (dblink is the pattern Ora2Pg can generate) and test the rollback case.

Can we lift package-heavy code onto Aurora DSQL?

Not as a lift-and-shift of typical package code. Aurora DSQL added PL/pgSQL functions, procedures and DO blocks on November 19, 2026, but the user guide says BEGIN ... EXCEPTION ... END blocks are not supported, and neither are explicit cursors (CURSOR / REFCURSOR, OPEN, FETCH, MOVE, CLOSE, and FOR ... IN cursor loops). Those are exactly the constructs a converted package tends to use. Target regular PostgreSQL (or Aurora PostgreSQL / RDS) for this work unless you have rewritten the exception and cursor paths.

Do %ROWTYPE and collections convert cleanly?

%ROWTYPE and %TYPE exist in PL/pgSQL and are usually a straightforward rewrite. Oracle associative arrays (index-by tables) and some nested collection patterns do not have a one-for-one type in PostgreSQL; arrays, jsonb or a temp table are the usual stand-ins, and they need tests. Do not assume a tool-converted collection still iterates or looks up the same way.

Where does this fit in the full Oracle to PostgreSQL migration?

In the conversion step, after you have a target schema design and before you lean on a cutover rehearsal. The nine-step plan is the spine; this post is the work inside “hand-convert what tools don’t” for packages, triggers and cursors.

Ready to scope a package?

If you have a set of PL/SQL packages, triggers and cursors to get onto PostgreSQL, we will size the leftover work, convert the state and transaction paths, and put a regression harness around them. Book a call.

Have a project like this?

We do this work for a living.

A 30-minute scoping call with the engineers who would do the work.

Or email contact@axiointelligence.com and we’ll reply.

Keep reading