Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL Error 39000: External Routine Invocation Exception

· 7 min read · Home Automation

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This error occurs when a PostgreSQL session attempts to call an external language routine and fails because the routine does not exist, the user lacks the required permission, the database cannot find the shared library file, or the function signature does not match the arguments provided. The fix involves verifying the function exists, checking the search path, ensuring library permissions, and aligning the function's argument list with the call.

What You'll Need

  • A PostgreSQL database server instance running and accessible.
  • Superuser access (typically the `postgres` role) to install shared libraries and modify permissions.
  • Access to the database where the function is defined (or a database accessible to the user calling it).
  • The source code or compiled shared object (.so) file for the external routine if you are installing a new one.
  • A text editor to write and execute SQL scripts.

Step-by-Step

  1. Confirm the Error Message Context
    When you see `ERROR: 39000: external routine invocation exception`, the message usually contains additional details like the specific function name, the library file name, or the exact line of code causing the failure. In PostgreSQL logs or the client output, look for the full error text. Often the real error is hidden behind this generic wrapper, such as a missing library or an invalid access mode. If the error log is unavailable, run a simple test query that triggers the routine to see the full stack trace in your SQL client.
  2. Verify the Function Exists and is Visible
    This is the most common cause. The database might have a function with a slightly different name or parameters. Connect to the database using the SQL client (e.g., `psql` or pgAdmin) and query the system catalog to list all functions with the language set to the external language you are using (e.g., `plpythonu`, `plperlu`, `c`, or a custom loader). Run a query like:
    SELECT proname, prosrc, lanname 
    FROM pg_proc 
    WHERE proname LIKE '%your_function_name%';
    If the function is missing, you must create it. If it exists but isn't visible, the issue is likely with the search_path configuration.
  3. Check and Fix the Search Path
    The PostgreSQL search path determines the order in which schemas are searched to resolve unqualified function names. If the function is defined in a schema that isn't first in the path, PostgreSQL cannot find it and throws the external routine invocation exception. You can check the current search path for the session with:
    SHOW search_path;
    To fix this, explicitly qualify the function call with its schema name (e.g., `myschema.my_function(param1)`), or modify the user's default search path settings. To change it permanently for a role, run:
    ALTER ROLE your_role SET search_path = 'myschema, public';
    If you are creating a function, ensure you do not rely on the first schema being empty or non-existent.
  4. Verify the Shared Library Path and Permissions
    For C-extensions or compiled languages (like `plpythonu` or `plperlu`), the database must be able to load the underlying shared library file. The error often manifests as 39000 if the file is missing or unreadable.
    • Locate the Library: Find the `.so` file on the server's filesystem. It is typically located in the `shared_preload_libraries` folder or a custom directory specified in the postgresql.conf file.
    • Check Permissions: Ensure the PostgreSQL service user (often `postgres` or `www-data`) has read and execute permissions on the directory containing the library and read permissions on the file itself. You can check this with the `ls -l` command on the server.
    • Verify `shared_preload_libraries`: If the library is a major extension, ensure the full path to the library is listed in the `shared_preload_libraries` configuration parameter in `postgresql.conf`. This parameter must be set before the server starts.
  5. Ensure the Function Signature Matches the Call
    The error can also occur if the arguments passed in the SQL query do not perfectly match the function's expected parameter types and count. PostgreSQL is strict about types. If you call a function expecting an integer but pass a string, it will fail to resolve the correct function and throw the invocation exception. Verify the data types of the arguments you are passing. For example, passing `'hello'` to a function expecting `integer` will cause a type mismatch during the routine invocation phase.
  6. Check User Privileges (EXECUTE Permission)
    Even if the function exists and the library is accessible, the user attempting to run the routine must have the `EXECUTE` privilege on it. A common oversight is that the user has permission to log in but lacks permission to run specific functions. Grant the privilege using:
    GRANT EXECUTE ON FUNCTION my_function(arg1_type, arg2_type) TO your_user;
    If the function is in a schema, you may also need `USAGE` privilege on that schema: `GRANT USAGE ON SCHEMA myschema TO your_user;`.
  7. Reload Configuration (If Necessary)
    If you modified the `shared_preload_libraries` or `search_path` settings in `postgresql.conf`, you must reload the configuration file without restarting the server to apply the changes. In most distributions, you can do this by running the command `pg_ctl reload` or by executing the SQL command `SELECT pg_reload_conf();` as a superuser.

Common Mistakes

  • Assuming a Function Exists: Developers often assume that because they can see the code in their local editor, the database knows about it. You must explicitly create the function in the database before calling it.
  • Ignoring Schema Qualification: Writing queries without schema prefixes relies on the search path. If a default schema is altered or the function is in an unexpected schema, the query fails. Always use the fully qualified name when possible.
  • Forgetting Library Permissions: The PostgreSQL server does not run as the superuser for every query in the same way a shell script might. It runs as a specific service account. If that account cannot read the `.so` file, the database will crash or throw this error.
  • Confusing `plpython` and `plpythonu`: `plpython` is for trusted execution (limited functionality), while `plpythonu` is untrusted. If you try to import modules in `plpython` that should require `plpythonu`, the invocation will fail.

Tips

  • Use `SET search_path` Locally: When debugging, you can set the search path for your current session to isolate the issue. `SET search_path TO public, my_custom_schema;` ensures you are always looking in the right place.
  • Clean Up Old Libraries: If you are reinstalling a shared library, ensure no stale versions of the file with the same name exist in the path, as the OS or database loader might load the wrong one.
  • Check the `log_min_messages` Setting: If the error happens silently or without a clear message, increase the logging level in `postgresql.conf` to `DEBUG1` or `LOG` to capture the exact reason for the library load failure.

Troubleshooting

If the steps above do not resolve the error, proceed with the following checks.

If the Function is Missing

Recreate the function using the `CREATE FUNCTION` statement. Ensure the language specified matches the external language you intend to use. For example, for Python:

CREATE FUNCTION process_data(data text) RETURNS integer
LANGUAGE plpythonu
AS $$
    # Python code here
    return 1
$$;

If the Library Cannot Be Found

Check the `libdir` setting in `postgresql.conf` to see where PostgreSQL looks for libraries. Ensure the path to your `.so` file is either inside that directory or listed in the `dynamic_library_path` configuration variable. You can verify the path PostgreSQL sees by running `SHOW dynamic_library_path;` inside the database.

If Permissions are Denied

Run the database server as a user that has read access to the directory containing your libraries. You can check the user the server runs as by looking at the process list: `ps aux | grep postgres`. If you cannot change the server user, copy the library files into the standard library directory (e.g., `/usr/lib/postgresql/x.y.z/lib`) and ensure the permissions are set to `644` (rw-r--r--).

If the Error Persists After Reload

A full restart of the PostgreSQL service is sometimes required to pick up changes to `shared_preload_libraries` or to fully unload a corrupted extension. Stop the service, start it again, and then retry the query.

Frequently Asked Questions

What does error 39000 mean in PostgreSQL?

It is a generic error code indicating that an external routine (like a C function, Python script, or Perl script) was invoked but failed. It is a wrapper error; the real cause is usually a missing library, a missing function, or a permission issue.

How do I grant permission to run a function?

Use the `GRANT EXECUTE ON FUNCTION` SQL command. You must specify the function name and the exact data types of its parameters for the command to work correctly.

Can I use any language in PostgreSQL?

No. PostgreSQL supports a limited set of languages by default: SQL, PL/pgSQL, C, and a few others like PL/Perl and PL/Python. You must install and load the specific language handler for other languages.

Why does my C extension cause this error?

This usually happens because the `.so` file is not in the `shared_preload_libraries` path, the file permissions are too restrictive for the postgres service user, or the function signature in the SQL query does not match the compiled C code.

Is it safe to run untrusted languages like Python?

Untrusted languages (indicated by the `u` suffix like `plpythonu`) can execute arbitrary code on the database server. They should only be used in trusted environments or specifically isolated databases, and only by users with high privileges.

How do I see the full error message?

Check the PostgreSQL log file (usually in `/var/log/postgresql/` or similar). The log file will contain the specific details about why the external routine failed, such as the missing file name or the Python traceback.