Re: Cast java.sql.Connection to PGConnection - Mailing list pgsql-jdbc

From David G. Johnston
Subject Re: Cast java.sql.Connection to PGConnection
Date
Msg-id CAKFQuwYOvib8hDfcpAJJXXsO32Jbt+1NFQHksNqCbLTaEwE3Hw@mail.gmail.com
Whole thread Raw
In response to Cast java.sql.Connection to PGConnection  ("peter.penzov" <peter.penzov@gmail.com>)
List pgsql-jdbc
I'm having trouble deciding which of the three emails from you to reply to.....

On Mon, May 2, 2016 at 11:29 AM, peter.penzov <peter.penzov@gmail.com> wrote:


I want to upload a file in PostgreSQL using Tomcat:

@Resource(name = "jdbc/DefaultDB")
private DataSource ds;
Connection conn = ds.getConnection();

I tried to cast the conn object this way:

PGConnection pgCon = ((org.apache.commons.dbcp.DelegatingConnection)
conn).getInnermostDelegate();

I get

Caused by: java.lang.ClassCastException:
org.apache.tomcat.dbcp.dbcp2.PoolingDataSource$PoolGuardConnectionWrapper
cannot be cast to org.postgresql.PGConnection


​OK.  So whatever Tomcat is doing under the hood its giving you a proxy object.  Given how connection pooling works this is not surprising.  The fact that it cannot be cast to org.postgresql.PGConnection is likewise unsurprising.  You are dealing with composition, not extension.​

I also tried:

Connection unwrap = conn.unwrap(Connection.class);
connSec = (org.postgresql.PGConnection) unwrap;

I get

java.sql.SQLException: Cannot unwrap to org.postgresql.PGConnection

No help here.  This isn't technically the correct list for problems about Tomcat classes though hopefully enough people on here actually use this stuff and can provide meaningful help.  Having not encountered this before I am not one of those people.

​I am confused how you call unwrap(Connection.class) and get an exception naming org.postgresql.PGConnection explicitly....​


LargeObjectManager pgCon = pgCon.getLargeObjectAPI();

What is the proper way to implement the code?

P.S

I tried this:

PGConnection pgConnection = null;

if (conn.isWrapperFor(PGConnection.class))
{
    pgConnection = conn.unwrap(PGConnection.class);
}

LargeObjectManager lobj = pgConnection.getLargeObjectAPI();

But I get NPE at this line LargeObjectManager lobj =
pgConnection.getLargeObjectAPI();


​Given the SQLException during the unwrap above this too is not surprising.

​Somwhere in the wrapping hierarchy someone seems to not be implementing the ​java.sql.Wrapper interface correctly or usefully.


PGConnection is at the end of this chain there isn't much the project itself can do.

David J.

pgsql-jdbc by date:

Previous
From: Dave Cramer
Date:
Subject: Re: PGConnection (LargeObject) / JNDI Tomcat Issue
Next
From: Gavin Flower
Date:
Subject: Re: pgsql jdbc db connection weird behaviour