JavaRush /Courses /SQL SELF /Debugging PL/pgSQL with pgAdmin: Breakpoints, Variable Wa...

Debugging PL/pgSQL with pgAdmin: Breakpoints, Variable Watch

SQL SELF
Level 56, Lesson 0
Available

So, you wrote your first procedure or function, ran it, but something went sideways. Sure, you could sprinkle a bunch of RAISE NOTICE statements to figure out where exactly your "ship hit the rocks." But! Why torture yourself if pgAdmin has a built-in debugger?

pgAdmin lets you step through your code, set breakpoints, check out variable values, and hunt down the root of errors. It's basically your "detective kit" for solving the mystery: "Why the heck isn't my query working?"

Why bother debugging with pgAdmin?

Sometimes bugs in your procedures are buried so deep that trying to figure them out just by reading logs or terminal output is pure pain. That's where step-by-step debugging saves the day—you see everything happening at each stage of your function. Think of it like putting together a crazy-hard puzzle, but with hints.

With debugging in pgAdmin, you can:

  1. Set breakpoints—these are spots where your code will pause so you can check out what's going on right then and there.
  2. Step through your SQL code—literally, go line by line and see which statement is running.
  3. See variable values in real time—make sure your data is being passed and processed right.
  4. Find where an error happened and figure out why.

Getting Started: Prepping for Debugging in pgAdmin

Before you start debugging, let's make sure everything's set up right.

Enabling the plpgsql Extension

Make sure your database has the PL/pgSQL programming language enabled:

CREATE EXTENSION IF NOT EXISTS plpgsql;

This language is usually enabled by default in PostgreSQL, but it's better to double-check.

Make sure you have pgAdmin version 4 or higher installed (it supports debugging). If you don't have it yet, you can download pgAdmin from the official site.

Installing the pldbgapi Extension

To enable PL/pgSQL debugging in pgAdmin, you need to activate the pldbgapi extension:

CREATE EXTENSION IF NOT EXISTS pldbgapi;

This extension is made specifically for working with the debugger.

Super important!!! Make sure you have admin rights on your PostgreSQL server to run this command.

Debugging Basics: Setting Breakpoints

Breakpoints are special spots in your code where the procedure or function will pause, giving you a chance to peek inside the process. It's like a quick pit stop on a long road trip: you stop, look around, check the map, then keep going.

How do you set a breakpoint in pgAdmin?

  1. Open pgAdmin and connect to your database.
  2. Find your function or procedure in the object tree: Functions → <your schema> → <your function>.
  3. Right-click the function and pick Debugging → Debug. This launches the debugger.
  4. In the window with your function's code, find the line where you want to start debugging and click in the margin to the left of the line. You'll see a red dot—that's your breakpoint.

Here's what it looks like:

CREATE OR REPLACE FUNCTION example_function(id INTEGER)
RETURNS VOID AS $$
BEGIN
    RAISE NOTICE 'You picked id: %', id;
    -- You can set a breakpoint here
    PERFORM some_operation(id);
END;
$$ LANGUAGE plpgsql;

Once the breakpoint is set, you can run your function, and execution will stop right there. Now you can check variable values, see what previous statements did, and of course, keep stepping through your code.

Watching Variables in pgAdmin

Knowing your code stopped is cool. But it's way more useful to see what data is in memory at that moment. For example:

  • What values the input parameters have.
  • How variables changed after a certain block ran.
  • What the query returned from the database.

How do you check variable values?

When your function pauses at a breakpoint:

  1. Go to the Variables tab at the bottom of the debugger window.
  2. Here you'll see a list of all variables and their current values.

Let's say you have a function like this:

CREATE OR REPLACE FUNCTION calculate_discount(price NUMERIC, discount NUMERIC)
RETURNS NUMERIC AS $$
DECLARE
    discounted_price NUMERIC;
BEGIN
    discounted_price := price - (price * discount / 100);
    RETURN discounted_price;
END;
$$ LANGUAGE plpgsql;

If you set a breakpoint on the line with discounted_price, the debugger will show that price and discount already have values, but discounted_price is still empty.

Here's what the variable list looks like after stopping:

Variable Value
price 100.00
discount 15.00
discounted_price NULL

After you run the current line, discounted_price will change to 85.00.

Stepping Through Code

In the debugger window, you can control your function's execution with these buttons:

  1. Step Over — runs the current statement and moves to the next one.
  2. Step Into — lets you "dive into" a called function or procedure.
  3. Continue — keeps running the function until the next breakpoint or until it's done.

Real-World Example: Debugging Complex Functions

Let's try writing and debugging a more complex function.

Example: processing orders

CREATE OR REPLACE FUNCTION process_order(order_id INTEGER)
RETURNS TEXT AS $$
DECLARE
    order_status TEXT;
    total_amount NUMERIC;
BEGIN
    -- Set order status
    SELECT status INTO order_status
    FROM orders
    WHERE id = order_id;

    IF order_status = 'Pending' THEN
        -- Calculate order total
        SELECT SUM(price * quantity) INTO total_amount
        FROM order_items
        WHERE order_id = order_id;

        -- Update order status
        UPDATE orders
        SET status = 'Processed', processed_date = NOW()
        WHERE id = order_id;

        RETURN 'Order processed. Total: ' || total_amount;
    ELSE
        RETURN 'Order already processed or does not exist.';
    END IF;
END;
$$ LANGUAGE plpgsql;

Possible breakpoints:

  1. On the line SELECT status INTO order_status.
  2. On the line SELECT SUM(price * quantity) INTO total_amount.

While debugging, you can:

  • Make sure order_status really is 'Pending'.
  • Check if total_amount is calculated correctly.

Common Errors and How to Fix Them

While debugging with pgAdmin, you might run into stuff like:

  1. You don't see your function in the list. Make sure the function is actually created in your database and you're connected to the right DB.
  1. Breakpoints don't work. Check if the pldbgapi extension is enabled and you have the right permissions.

  2. Debugger connection error. Make sure your PostgreSQL server is set up for debugging (the shared_preload_libraries parameter includes pldbgapi).

Using pgAdmin to debug PL/pgSQL makes the whole debugging process super easy and intuitive. Set a breakpoint, see what your variables are up to, and fix all the bugs—that's already halfway to your perfect app!

2
Task
SQL SELF, level 56, lesson 0
Locked
Debugging a function with multiple variables
Debugging a function with multiple variables
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION