Postgres JDBC driver not returning error line number as shown in PGAdmin

Viewed 269

Postgres JDBC driver not returning the exact error line number as shown in PGAdmin. When I run the below program :

import java.sql.*;

public class Test {

  public static void main(String[] args) {

    String query = "SELECT table_name, table_type\n" +
      "  FROM information_schema.tabls\n" +
      " WHERE table_schema='public'\n" +
      "   AND table_type in ('BASE TABLE','VIEW') ORDER BY table_type, table_name;";

    try (Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres")) {

      System.out.println("Connected to PostgreSQL database!");
      Statement statement = connection.createStatement();
      ResultSet resultSet = statement.executeQuery(query);
      while (resultSet.next()) {
        System.out.printf("%-30.30s  %-30.30s%n", resultSet.getString("table_name"), resultSet.getString("table_type"));
      }

    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}

I am getting the following error :

 org.postgresql.util.PSQLException: ERROR: relation "information_schema.tabls" does not exist
  Position: 38

But when I run the same query on pgadmin4, I receive the following error :

    ERROR:  relation "information_schema.tabls" does not exist
LINE 2:   FROM information_schema.tabls
               ^
SQL state: 42P01
Character: 38

I want the line number in java program as well. How can I get it?

1 Answers

PGAdmin4 is a node.js backend that uses Python driver psycopg2. This driver is nothing more than a wrapper for C driver named libpq, created by the PostgreSQL team.

JDBC driver communicates with database and uses responses received from the server. org.postgresql.core.v3.QueryExecutorImpl#receiveNoticeResponse private method responsible for parsing server errors and it just creates new org.postgresql.util.ServerErrorMessage instance. So, the response given by the server is equal to the response shown by the JDBC driver.

But as for libpq, messages received from the server, and shown on client-side aren't the same. There is reportErrorPosition method in libpq sources exactly for adding line information. Here is reference for reportErrorPosition sources for PostgreSQL 13.3. Here is place where LINE: x is added to the client error.

Summary

You need to calculate the line number by yourself when using the JDBC driver. Or use C library which does it for you.

Related