pg.ddx.io  pgsql-jdbc@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Timestamp vs. Java Date/Timestamp
13+ messages / 4 participants
[nested] [flat]

* Timestamp vs. Java Date/Timestamp
@ 2013-02-05 05:47  Andreas Reichel <andreas@manticore-projects.com>
  0 siblings, 2 replies; 13+ messages in thread

From: Andreas Reichel @ 2013-02-05 05:47 UTC (permalink / raw)
  To: pgsql-jdbc

Dear List,

the last day I had a hard time figuring out how to hand over timestamps
using prepared statements.

The table looks like this:

trader=# \d trader.tickdata
                   Table "trader.tickdata"
      Column       |            Type             | Modifiers 
-------------------+-----------------------------+-----------
 id_instrument     | smallint                    | not null
 id_stock_exchange | smallint                    | not null
 timestamp         | timestamp without time zone | not null
 price             | double precision            | not null


Now I would like to retrieve ticks using a prepared statement like this:

-- GET TICKDATA
select 
	t1.id_instrument, 
	t1.id_stock_exchange, 
	t1."timestamp", 
	t1.price, 
	coalesce(t2.quantity,0) quantity 
from 
	trader.tickdata t1 
	left join trader.volumedata t2 
		ON (t1.id_instrument=t2.id_instrument AND
t1.id_stock_exchange=t2.id_stock_exchange AND
t1."timestamp"=t2."timestamp") 
where 
	t1.id_instrument= ?
	AND t1.id_stock_exchange= ?
	--careful with TIMEZONE here!
	AND t1."timestamp">= ?
	AND t1."timestamp"<= ?
ORDER BY t1."timestamp" ASC;

If I hand over java.util.Date or java.sql.Date or java.sql.Timestamp the
query will be executed but returns the wrong number of records;

However, if I change the query into:
-- GET TICKDATA
select 
	t1.id_instrument, 
	t1.id_stock_exchange, 
	t1."timestamp", 
	t1.price, 
	coalesce(t2.quantity,0) quantity 
from 
	trader.tickdata t1 
	left join trader.volumedata t2 
		ON (t1.id_instrument=t2.id_instrument AND
t1.id_stock_exchange=t2.id_stock_exchange AND
t1."timestamp"=t2."timestamp") 
where 
	t1.id_instrument= ?
	AND t1.id_stock_exchange= ?
	--careful with TIMEZONE here!
	AND t1."timestamp">= cast(? as timestamp)
	AND t1."timestamp"<= cast(? as timestamp)
ORDER BY t1."timestamp" ASC;

and hand over a formated date "yyyy-MM-dd HH:mm:ss" it works correctly.
Now I have on simple questions please:

What is the correct way to hand over a Java Date parameter (avoiding the
double String manipulation)?

Thank you and best regards!
Andreas




-- 
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc



^ permalink  raw  reply  [nested|flat] 13+ messages in thread

* Re: Timestamp vs. Java Date/Timestamp
@ 2013-02-05 14:42  Dave Cramer <pg@fastcrypt.com>
  parent: Andreas Reichel <andreas@manticore-projects.com>
  1 sibling, 4 replies; 13+ messages in thread

From: Dave Cramer @ 2013-02-05 14:42 UTC (permalink / raw)
  To: Andreas Reichel <andreas@manticore-projects.com>; +Cc: pgsql-jdbc

Andreas,

What are you using to setTimestamp in the prepared statement ? setDate or
setTimestamp ?

Dave Cramer

dave.cramer(at)credativ(dot)ca
http://www.credativ.ca


On Tue, Feb 5, 2013 at 12:47 AM, Andreas Reichel <
andreas@manticore-projects.com> wrote:

> Dear List,
>
> the last day I had a hard time figuring out how to hand over timestamps
> using prepared statements.
>
> The table looks like this:
>
> trader=# \d trader.tickdata
>                    Table "trader.tickdata"
>       Column       |            Type             | Modifiers
> -------------------+-----------------------------+-----------
>  id_instrument     | smallint                    | not null
>  id_stock_exchange | smallint                    | not null
>  timestamp         | timestamp without time zone | not null
>  price             | double precision            | not null
>
>
> Now I would like to retrieve ticks using a prepared statement like this:
>
> -- GET TICKDATA
> select
>         t1.id_instrument,
>         t1.id_stock_exchange,
>         t1."timestamp",
>         t1.price,
>         coalesce(t2.quantity,0) quantity
> from
>         trader.tickdata t1
>         left join trader.volumedata t2
>                 ON (t1.id_instrument=t2.id_instrument AND
> t1.id_stock_exchange=t2.id_stock_exchange AND
> t1."timestamp"=t2."timestamp")
> where
>         t1.id_instrument= ?
>         AND t1.id_stock_exchange= ?
>         --careful with TIMEZONE here!
>         AND t1."timestamp">= ?
>         AND t1."timestamp"<= ?
> ORDER BY t1."timestamp" ASC;
>
> If I hand over java.util.Date or java.sql.Date or java.sql.Timestamp the
> query will be executed but returns the wrong number of records;
>
> However, if I change the query into:
> -- GET TICKDATA
> select
>         t1.id_instrument,
>         t1.id_stock_exchange,
>         t1."timestamp",
>         t1.price,
>         coalesce(t2.quantity,0) quantity
> from
>         trader.tickdata t1
>         left join trader.volumedata t2
>                 ON (t1.id_instrument=t2.id_instrument AND
> t1.id_stock_exchange=t2.id_stock_exchange AND
> t1."timestamp"=t2."timestamp")
> where
>         t1.id_instrument= ?
>         AND t1.id_stock_exchange= ?
>         --careful with TIMEZONE here!
>         AND t1."timestamp">= cast(? as timestamp)
>         AND t1."timestamp"<= cast(? as timestamp)
> ORDER BY t1."timestamp" ASC;
>
> and hand over a formated date "yyyy-MM-dd HH:mm:ss" it works correctly.
> Now I have on simple questions please:
>
> What is the correct way to hand over a Java Date parameter (avoiding the
> double String manipulation)?
>
> Thank you and best regards!
> Andreas
>
>
>
>
> --
> Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
> To make changes to your subscription:
> http://www.postgresql.org/mailpref/pgsql-jdbc
>

^ permalink  raw  reply  [nested|flat] 13+ messages in thread

* Re: Timestamp vs. Java Date/Timestamp
@ 2013-02-05 15:07  Thomas Kellerer <spam_eater@gmx.net>
  parent: Andreas Reichel <andreas@manticore-projects.com>
  1 sibling, 0 replies; 13+ messages in thread

From: Thomas Kellerer @ 2013-02-05 15:07 UTC (permalink / raw)
  To: pgsql-jdbc

Andreas Reichel, 05.02.2013 06:47:
> Dear List,
>
> the last day I had a hard time figuring out how to hand over timestamps
> using prepared statements.
>
> What is the correct way to hand over a Java Date parameter (avoiding the
> double String manipulation)?

Pass an instance of java.sql.Timestamp using the setTimestamp() method.






-- 
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc



^ permalink  raw  reply  [nested|flat] 13+ messages in thread

* Re: Timestamp vs. Java Date/Timestamp
@ 2013-02-06 02:38  Andreas Reichel <andreas@manticore-projects.com>
  parent: Dave Cramer <pg@fastcrypt.com>
  3 siblings, 0 replies; 13+ messages in thread

From: Andreas Reichel @ 2013-02-06 02:38 UTC (permalink / raw)
  To: Dave Cramer <pg@fastcrypt.com>; +Cc: pgsql-jdbc

Hi Dave,

I tried setObject() handing over java.util.Date or java.sql.Date.
Furthermore I tried setDate() (which enforces java.sql.Date) and
setTimestamp (which enforces java,sql.Timestamp). It all failed the same
way.


Best regards
Andreas


On Tue, 2013-02-05 at 09:42 -0500, Dave Cramer wrote:
> Andreas,
> 
> 
> What are you using to setTimestamp in the prepared statement ? setDate
> or setTimestamp ?
> 
> Dave Cramer
> 
> dave.cramer(at)credativ(dot)ca
> http://www.credativ.ca
> 
> 
> 
> On Tue, Feb 5, 2013 at 12:47 AM, Andreas Reichel
> <andreas@manticore-projects.com> wrote:
>         Dear List,
>         
>         the last day I had a hard time figuring out how to hand over
>         timestamps
>         using prepared statements.
>         
>         The table looks like this:
>         
>         trader=# \d trader.tickdata
>                            Table "trader.tickdata"
>               Column       |            Type             | Modifiers
>         -------------------+-----------------------------+-----------
>          id_instrument     | smallint                    | not null
>          id_stock_exchange | smallint                    | not null
>          timestamp         | timestamp without time zone | not null
>          price             | double precision            | not null
>         
>         
>         Now I would like to retrieve ticks using a prepared statement
>         like this:
>         
>         -- GET TICKDATA
>         select
>                 t1.id_instrument,
>                 t1.id_stock_exchange,
>                 t1."timestamp",
>                 t1.price,
>                 coalesce(t2.quantity,0) quantity
>         from
>                 trader.tickdata t1
>                 left join trader.volumedata t2
>                         ON (t1.id_instrument=t2.id_instrument AND
>         t1.id_stock_exchange=t2.id_stock_exchange AND
>         t1."timestamp"=t2."timestamp")
>         where
>                 t1.id_instrument= ?
>                 AND t1.id_stock_exchange= ?
>                 --careful with TIMEZONE here!
>                 AND t1."timestamp">= ?
>                 AND t1."timestamp"<= ?
>         ORDER BY t1."timestamp" ASC;
>         
>         If I hand over java.util.Date or java.sql.Date or
>         java.sql.Timestamp the
>         query will be executed but returns the wrong number of
>         records;
>         
>         However, if I change the query into:
>         -- GET TICKDATA
>         select
>                 t1.id_instrument,
>                 t1.id_stock_exchange,
>                 t1."timestamp",
>                 t1.price,
>                 coalesce(t2.quantity,0) quantity
>         from
>                 trader.tickdata t1
>                 left join trader.volumedata t2
>                         ON (t1.id_instrument=t2.id_instrument AND
>         t1.id_stock_exchange=t2.id_stock_exchange AND
>         t1."timestamp"=t2."timestamp")
>         where
>                 t1.id_instrument= ?
>                 AND t1.id_stock_exchange= ?
>                 --careful with TIMEZONE here!
>                 AND t1."timestamp">= cast(? as timestamp)
>                 AND t1."timestamp"<= cast(? as timestamp)
>         ORDER BY t1."timestamp" ASC;
>         
>         and hand over a formated date "yyyy-MM-dd HH:mm:ss" it works
>         correctly.
>         Now I have on simple questions please:
>         
>         What is the correct way to hand over a Java Date parameter
>         (avoiding the
>         double String manipulation)?
>         
>         Thank you and best regards!
>         Andreas
>         
>         
>         
>         
>         --
>         Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
>         To make changes to your subscription:
>         http://www.postgresql.org/mailpref/pgsql-jdbc
> 
> 




-- 
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc



^ permalink  raw  reply  [nested|flat] 13+ messages in thread

* Re: Timestamp vs. Java Date/Timestamp
@ 2013-02-06 03:01  Andreas Reichel <andreas@manticore-projects.com>
  parent: Dave Cramer <pg@fastcrypt.com>
  3 siblings, 0 replies; 13+ messages in thread

From: Andreas Reichel @ 2013-02-06 03:01 UTC (permalink / raw)
  To: Dave Cramer <pg@fastcrypt.com>; +Cc: pgsql-jdbc

Dave, my apologies for a rather long posting, perhaps I found what
happens:

//--------------------------------------------------------------------
// Step 1: hand over a Date calls setDate without Calendar, good:

 case Types.DATE:
	            if (in instanceof java.sql.Date)
	                setDate(parameterIndex, (java.sql.Date)in);
	            else
	            {
	                java.sql.Date tmpd;
	                if (in instanceof java.util.Date) {
	                    tmpd = new
java.sql.Date(((java.util.Date)in).getTime());
	                } else {
	                    tmpd = connection.getTimestampUtils().toDate(null,
in.toString());
	                }
	                setDate(parameterIndex, tmpd);
	            }
	            break;
	            

//--------------------------------------------------------------------
// Step 2: setDate calls setDate with Calendar==NULL:

    public void setDate(int parameterIndex, java.sql.Date x) throws
SQLException
    {
        setDate(parameterIndex, x, null);
    }
    
//--------------------------------------------------------------------
// Step 3: setDate with Calendar==NULL calls TimeStampUtils with empty
TimeZone:

    public void setDate(int i, java.sql.Date d, java.util.Calendar cal)
throws SQLException
    {
        checkClosed();

        if (d == null)
        {
            setNull(i, Types.DATE);
            return;
        }

        if (connection.binaryTransferSend(Oid.DATE)) {
            byte[] val = new byte[4];
            TimeZone tz = cal != null ? cal.getTimeZone() : null;
            connection.getTimestampUtils().toBinDate(tz, val, d);
            preparedParameters.setBinaryParameter(i, val, Oid.DATE);
            return;
        }
        
        if (cal != null)
            cal = (Calendar)cal.clone();

        // We must use UNSPECIFIED here, or inserting a
Date-with-timezone into a
        // timestamptz field does an unexpected rotation by the server's
TimeZone:
        //
        // We want to interpret 2005/01/01 with calendar +0100 as
        // "local midnight in +0100", but if we go via date it
interprets it
        // as local midnight in the server's timezone:

        // template1=# select '2005-01-01+0100'::timestamptz;
        //       timestamptz       
        // ------------------------
        //  2005-01-01 02:00:00+03
        // (1 row)

        // template1=# select '2005-01-01+0100'::date::timestamptz;
        //       timestamptz       
        // ------------------------
        //  2005-01-01 00:00:00+03
        // (1 row)

        bindString(i, connection.getTimestampUtils().toString(cal, d),
Oid.UNSPECIFIED);
    }
    
//--------------------------------------------------------------------
// Step 4: when TimeZone is empty, the defaultTZ is used --> Why?! I
have a field which is WITHOUT Timezone for good reasons

    public void toBinDate(TimeZone tz, byte[] bytes, Date value) throws
PSQLException {
        long millis = value.getTime();
        
        if (tz == null) {
            tz = defaultTz;
        }
        millis += tz.getOffset(millis);
        
        long secs = toPgSecs(millis / 1000);
        ByteConverter.int4(bytes, 0, (int) (secs / 86400));
    }


I would like to suggest to modify the toBinDate() and to add
tz.getOffset(millis) ONLY if a Timezone was specified, but not when
NULL:

	public void toBinDate(TimeZone tz, byte[] bytes, Date value) throws
PSQLException {
        long millis = value.getTime();
        
        if (tz != null) {
            millis += tz.getOffset(millis);
        }
        
        long secs = toPgSecs(millis / 1000);
        ByteConverter.int4(bytes, 0, (int) (secs / 86400));
    }

What do you think?

Best regards
Andreas



-- 
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc



^ permalink  raw  reply  [nested|flat] 13+ messages in thread

* Re: Timestamp vs. Java Date/Timestamp
@ 2013-02-06 04:11  Andreas Reichel <andreas@manticore-projects.com>
  parent: Dave Cramer <pg@fastcrypt.com>
  3 siblings, 1 reply; 13+ messages in thread

From: Andreas Reichel @ 2013-02-06 04:11 UTC (permalink / raw)
  To: Dave Cramer <pg@fastcrypt.com>; +Cc: pgsql-jdbc

Dave,

my previous post was not correct, but I finally found the culprit:

For any reason we use bindString:

bindString(i, connection.getTimestampUtils().toString(cal, d),
Oid.UNSPECIFIED);

which formats Date into a String, but without information on the time:

public synchronized String toString(Calendar cal, Date x) {
        if (cal == null)
            cal = defaultCal;

        cal.setTime(x);
        sbuf.setLength(0);
        
        if (x.getTime() == PGStatement.DATE_POSITIVE_INFINITY) {
            sbuf.append("infinity");
        } else if (x.getTime() == PGStatement.DATE_NEGATIVE_INFINITY) {
            sbuf.append("-infinity");
        } else {
// the date only but no time
            appendDate(sbuf, cal);
//
            appendEra(sbuf, cal);
            appendTimeZone(sbuf, cal);
        }
        
        showString("date", cal, x, sbuf.toString());
        
        return sbuf.toString();
    }

When I modified this function into:

public synchronized String toString(Calendar cal, Date x) {
        if (cal == null)
            cal = defaultCal;

        cal.setTime(x);
        sbuf.setLength(0);
        
        if (x.getTime() == PGStatement.DATE_POSITIVE_INFINITY) {
            sbuf.append("infinity");
        } else if (x.getTime() == PGStatement.DATE_NEGATIVE_INFINITY) {
            sbuf.append("-infinity");
        } else {
            appendDate(sbuf, cal);

// obey the time too as java.util.Date holds the time
            sbuf.append(" ");
            appendTime(sbuf, cal, 0);
//
            appendEra(sbuf, cal);
            appendTimeZone(sbuf, cal);
        }
        
        showString("date", cal, x, sbuf.toString());
        
        return sbuf.toString();
    }

everything works as expected and also everything else still worked well.
(My program uses a lot of date/time conversions so I have some
confidence).

Now there are two questions please:

a) would you like to apply this small change because java.util.Date
holds time information so we should obey it

b) why is there all this Date/String conversion instead just using
millis/Long? I expected using setDate() gives better performance than
handing over Strings but now I found that it does exactly the same and
in an unexpected way?

Best regards
Andreas




On Tue, 2013-02-05 at 09:42 -0500, Dave Cramer wrote:
> Andreas,
> 
> 
> What are you using to setTimestamp in the prepared statement ? setDate
> or setTimestamp ?
> 
> Dave Cramer
> 
> dave.cramer(at)credativ(dot)ca
> http://www.credativ.ca
> 
> 
> 
> On Tue, Feb 5, 2013 at 12:47 AM, Andreas Reichel
> <andreas@manticore-projects.com> wrote:
>         Dear List,
>         
>         the last day I had a hard time figuring out how to hand over
>         timestamps
>         using prepared statements.
>         
>         The table looks like this:
>         
>         trader=# \d trader.tickdata
>                            Table "trader.tickdata"
>               Column       |            Type             | Modifiers
>         -------------------+-----------------------------+-----------
>          id_instrument     | smallint                    | not null
>          id_stock_exchange | smallint                    | not null
>          timestamp         | timestamp without time zone | not null
>          price             | double precision            | not null
>         
>         
>         Now I would like to retrieve ticks using a prepared statement
>         like this:
>         
>         -- GET TICKDATA
>         select
>                 t1.id_instrument,
>                 t1.id_stock_exchange,
>                 t1."timestamp",
>                 t1.price,
>                 coalesce(t2.quantity,0) quantity
>         from
>                 trader.tickdata t1
>                 left join trader.volumedata t2
>                         ON (t1.id_instrument=t2.id_instrument AND
>         t1.id_stock_exchange=t2.id_stock_exchange AND
>         t1."timestamp"=t2."timestamp")
>         where
>                 t1.id_instrument= ?
>                 AND t1.id_stock_exchange= ?
>                 --careful with TIMEZONE here!
>                 AND t1."timestamp">= ?
>                 AND t1."timestamp"<= ?
>         ORDER BY t1."timestamp" ASC;
>         
>         If I hand over java.util.Date or java.sql.Date or
>         java.sql.Timestamp the
>         query will be executed but returns the wrong number of
>         records;
>         
>         However, if I change the query into:
>         -- GET TICKDATA
>         select
>                 t1.id_instrument,
>                 t1.id_stock_exchange,
>                 t1."timestamp",
>                 t1.price,
>                 coalesce(t2.quantity,0) quantity
>         from
>                 trader.tickdata t1
>                 left join trader.volumedata t2
>                         ON (t1.id_instrument=t2.id_instrument AND
>         t1.id_stock_exchange=t2.id_stock_exchange AND
>         t1."timestamp"=t2."timestamp")
>         where
>                 t1.id_instrument= ?
>                 AND t1.id_stock_exchange= ?
>                 --careful with TIMEZONE here!
>                 AND t1."timestamp">= cast(? as timestamp)
>                 AND t1."timestamp"<= cast(? as timestamp)
>         ORDER BY t1."timestamp" ASC;
>         
>         and hand over a formated date "yyyy-MM-dd HH:mm:ss" it works
>         correctly.
>         Now I have on simple questions please:
>         
>         What is the correct way to hand over a Java Date parameter
>         (avoiding the
>         double String manipulation)?
>         
>         Thank you and best regards!
>         Andreas
>         
>         
>         
>         
>         --
>         Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
>         To make changes to your subscription:
>         http://www.postgresql.org/mailpref/pgsql-jdbc
> 
> 




-- 
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc



^ permalink  raw  reply  [nested|flat] 13+ messages in thread

* Re: Timestamp vs. Java Date/Timestamp
@ 2013-02-08 14:13  Dave Cramer <pg@fastcrypt.com>
  parent: Andreas Reichel <andreas@manticore-projects.com>
  0 siblings, 2 replies; 13+ messages in thread

From: Dave Cramer @ 2013-02-08 14:13 UTC (permalink / raw)
  To: Andreas Reichel <andreas@manticore-projects.com>; +Cc: pgsql-jdbc

Andreas this does not pass the built in tests. run ant test to see

Dave Cramer

dave.cramer(at)credativ(dot)ca
http://www.credativ.ca


On Tue, Feb 5, 2013 at 11:11 PM, Andreas Reichel <
andreas@manticore-projects.com> wrote:

> Dave,
>
> my previous post was not correct, but I finally found the culprit:
>
> For any reason we use bindString:
>
> bindString(i, connection.getTimestampUtils().toString(cal, d),
> Oid.UNSPECIFIED);
>
> which formats Date into a String, but without information on the time:
>
> public synchronized String toString(Calendar cal, Date x) {
>         if (cal == null)
>             cal = defaultCal;
>
>         cal.setTime(x);
>         sbuf.setLength(0);
>
>         if (x.getTime() == PGStatement.DATE_POSITIVE_INFINITY) {
>             sbuf.append("infinity");
>         } else if (x.getTime() == PGStatement.DATE_NEGATIVE_INFINITY) {
>             sbuf.append("-infinity");
>         } else {
> // the date only but no time
>             appendDate(sbuf, cal);
> //
>             appendEra(sbuf, cal);
>             appendTimeZone(sbuf, cal);
>         }
>
>         showString("date", cal, x, sbuf.toString());
>
>         return sbuf.toString();
>     }
>
> When I modified this function into:
>
> public synchronized String toString(Calendar cal, Date x) {
>         if (cal == null)
>             cal = defaultCal;
>
>         cal.setTime(x);
>         sbuf.setLength(0);
>
>         if (x.getTime() == PGStatement.DATE_POSITIVE_INFINITY) {
>             sbuf.append("infinity");
>         } else if (x.getTime() == PGStatement.DATE_NEGATIVE_INFINITY) {
>             sbuf.append("-infinity");
>         } else {
>             appendDate(sbuf, cal);
>
> // obey the time too as java.util.Date holds the time
>             sbuf.append(" ");
>             appendTime(sbuf, cal, 0);
> //
>             appendEra(sbuf, cal);
>             appendTimeZone(sbuf, cal);
>         }
>
>         showString("date", cal, x, sbuf.toString());
>
>         return sbuf.toString();
>     }
>
> everything works as expected and also everything else still worked well.
> (My program uses a lot of date/time conversions so I have some
> confidence).
>
> Now there are two questions please:
>
> a) would you like to apply this small change because java.util.Date
> holds time information so we should obey it
>
> b) why is there all this Date/String conversion instead just using
> millis/Long? I expected using setDate() gives better performance than
> handing over Strings but now I found that it does exactly the same and
> in an unexpected way?
>
> Best regards
> Andreas
>
>
>
>
> On Tue, 2013-02-05 at 09:42 -0500, Dave Cramer wrote:
> > Andreas,
> >
> >
> > What are you using to setTimestamp in the prepared statement ? setDate
> > or setTimestamp ?
> >
> > Dave Cramer
> >
> > dave.cramer(at)credativ(dot)ca
> > http://www.credativ.ca
> >
> >
> >
> > On Tue, Feb 5, 2013 at 12:47 AM, Andreas Reichel
> > <andreas@manticore-projects.com> wrote:
> >         Dear List,
> >
> >         the last day I had a hard time figuring out how to hand over
> >         timestamps
> >         using prepared statements.
> >
> >         The table looks like this:
> >
> >         trader=# \d trader.tickdata
> >                            Table "trader.tickdata"
> >               Column       |            Type             | Modifiers
> >         -------------------+-----------------------------+-----------
> >          id_instrument     | smallint                    | not null
> >          id_stock_exchange | smallint                    | not null
> >          timestamp         | timestamp without time zone | not null
> >          price             | double precision            | not null
> >
> >
> >         Now I would like to retrieve ticks using a prepared statement
> >         like this:
> >
> >         -- GET TICKDATA
> >         select
> >                 t1.id_instrument,
> >                 t1.id_stock_exchange,
> >                 t1."timestamp",
> >                 t1.price,
> >                 coalesce(t2.quantity,0) quantity
> >         from
> >                 trader.tickdata t1
> >                 left join trader.volumedata t2
> >                         ON (t1.id_instrument=t2.id_instrument AND
> >         t1.id_stock_exchange=t2.id_stock_exchange AND
> >         t1."timestamp"=t2."timestamp")
> >         where
> >                 t1.id_instrument= ?
> >                 AND t1.id_stock_exchange= ?
> >                 --careful with TIMEZONE here!
> >                 AND t1."timestamp">= ?
> >                 AND t1."timestamp"<= ?
> >         ORDER BY t1."timestamp" ASC;
> >
> >         If I hand over java.util.Date or java.sql.Date or
> >         java.sql.Timestamp the
> >         query will be executed but returns the wrong number of
> >         records;
> >
> >         However, if I change the query into:
> >         -- GET TICKDATA
> >         select
> >                 t1.id_instrument,
> >                 t1.id_stock_exchange,
> >                 t1."timestamp",
> >                 t1.price,
> >                 coalesce(t2.quantity,0) quantity
> >         from
> >                 trader.tickdata t1
> >                 left join trader.volumedata t2
> >                         ON (t1.id_instrument=t2.id_instrument AND
> >         t1.id_stock_exchange=t2.id_stock_exchange AND
> >         t1."timestamp"=t2."timestamp")
> >         where
> >                 t1.id_instrument= ?
> >                 AND t1.id_stock_exchange= ?
> >                 --careful with TIMEZONE here!
> >                 AND t1."timestamp">= cast(? as timestamp)
> >                 AND t1."timestamp"<= cast(? as timestamp)
> >         ORDER BY t1."timestamp" ASC;
> >
> >         and hand over a formated date "yyyy-MM-dd HH:mm:ss" it works
> >         correctly.
> >         Now I have on simple questions please:
> >
> >         What is the correct way to hand over a Java Date parameter
> >         (avoiding the
> >         double String manipulation)?
> >
> >         Thank you and best regards!
> >         Andreas
> >
> >
> >
> >
> >         --
> >         Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
> >         To make changes to your subscription:
> >         http://www.postgresql.org/mailpref/pgsql-jdbc
> >
> >
>
>
>

^ permalink  raw  reply  [nested|flat] 13+ messages in thread

* Re: Timestamp vs. Java Date/Timestamp
@ 2013-02-08 19:09  dmp <danap@ttc-cmc.net>
  parent: Dave Cramer <pg@fastcrypt.com>
  1 sibling, 0 replies; 13+ messages in thread

From: dmp @ 2013-02-08 19:09 UTC (permalink / raw)
  To: Dave Cramer <pg@fastcrypt.com>; pgsql-jdbc

Andreas,

I guess I should have replied back sooner, but it looked like the
problem you were having and the question you originally asked was
handled. Perhaps I can get some feedback to the original question
before, Dave, the JDBC is modified to effect the Date formmatting.

QUESTION: What is the proper way to handle the TIMESTAMP type in
           PostgreSQL with a prepare statement? NOT TIMESTAMPTZ.
           Without all this parsing of date and time with string.
           Implying you are using java.util.Date in your app.

First the a DATE type in the database is not the same as a java.util.Date
in Java. The later does hold a time, and though the java.sql.Date is
define generally as a thinnly wrapped java.util.Date the last time
I checked NO database returns time with their DATE types. So with
this statement I'm questioning the change Andrea you have requested,
but do not see a problem with the patch, beside as already noted
by Dave the failing of the test routine.

Now one of my projects works with several database including
PostgreSQL and I have found the problems that occur most fequently
are when trying to adapt the app. to a multitute of temporal types.

Example:

DATE
TIME
TIMETZ
DATETIME
TIMESTAMP
TIMESTAMPTZ
TIMESTAMPLTZ
YEAR

So I looked at specifically how I have handle TIMESTAMP types
in PostgreSQL with Preparedstatements and this is the solution
I used. Though it may not be the proper way, it does seem
to work. Note this approach can also be used with TIMESTAMPTZ
also by modifying the SimpleDateFormat and allows using
different DATE formats as illusttrated.

SimpleDateFormat timeStampFormat;
java.sql.Timestamp dateTimeValue;
java.util.Date dateParse;

timeStampFormat = new SimpleDateFormat("MM-dd-yyyy" + " HH:mm:ss");
dateParse = timeStampFormat.parse("12-30-2008 15:16:08");
dateTimeValue = new java.sql.Timestamp(dateParse.getTime());
prepared_sqlStatement.setTimestamp(i, dateTimeValue);

Perhaps this may help.

danap.


Dave Cramer wrote:
>
> Andreas this does not pass the built in tests. run ant test to see
>
> Dave Cramer
>
> dave.cramer(at)credativ(dot)ca
> http://www.credativ.ca
>
>
> On Tue, Feb 5, 2013 at 11:11 PM, Andreas Reichel
> <andreas@manticore-projects.com <mailto:andreas@manticore-projects.com>>
> wrote:
>
>     Dave,
>
>     my previous post was not correct, but I finally found the culprit:
>
>     For any reason we use bindString:
>
>     bindString(i, connection.getTimestampUtils().toString(cal, d),
>     Oid.UNSPECIFIED);
>
>     which formats Date into a String, but without information on the time:
>
>     public synchronized String toString(Calendar cal, Date x) {
>              if (cal == null)
>                  cal = defaultCal;
>
>              cal.setTime(x);
>              sbuf.setLength(0);
>
>              if (x.getTime() == PGStatement.DATE_POSITIVE_INFINITY) {
>                  sbuf.append("infinity");
>              } else if (x.getTime() == PGStatement.DATE_NEGATIVE_INFINITY) {
>                  sbuf.append("-infinity");
>              } else {
>     // the date only but no time
>                  appendDate(sbuf, cal);
>     //
>                  appendEra(sbuf, cal);
>                  appendTimeZone(sbuf, cal);
>              }
>
>              showString("date", cal, x, sbuf.toString());
>
>              return sbuf.toString();
>          }
>
>     When I modified this function into:
>
>     public synchronized String toString(Calendar cal, Date x) {
>              if (cal == null)
>                  cal = defaultCal;
>
>              cal.setTime(x);
>              sbuf.setLength(0);
>
>              if (x.getTime() == PGStatement.DATE_POSITIVE_INFINITY) {
>                  sbuf.append("infinity");
>              } else if (x.getTime() == PGStatement.DATE_NEGATIVE_INFINITY) {
>                  sbuf.append("-infinity");
>              } else {
>                  appendDate(sbuf, cal);
>
>     // obey the time too as java.util.Date holds the time
>                  sbuf.append(" ");
>                  appendTime(sbuf, cal, 0);
>     //
>                  appendEra(sbuf, cal);
>                  appendTimeZone(sbuf, cal);
>              }
>
>              showString("date", cal, x, sbuf.toString());
>
>              return sbuf.toString();
>          }
>
>     everything works as expected and also everything else still worked well.
>     (My program uses a lot of date/time conversions so I have some
>     confidence).
>
>     Now there are two questions please:
>
>     a) would you like to apply this small change because java.util.Date
>     holds time information so we should obey it
>
>     b) why is there all this Date/String conversion instead just using
>     millis/Long? I expected using setDate() gives better performance than
>     handing over Strings but now I found that it does exactly the same and
>     in an unexpected way?
>
>     Best regards
>     Andreas
>
>
>
>
>     On Tue, 2013-02-05 at 09:42 -0500, Dave Cramer wrote:
>      > Andreas,
>      >
>      >
>      > What are you using to setTimestamp in the prepared statement ?
>     setDate
>      > or setTimestamp ?
>      >
>      > Dave Cramer
>      >
>      > dave.cramer(at)credativ(dot)ca
>      > http://www.credativ.ca
>      >
>      >
>      >
>      > On Tue, Feb 5, 2013 at 12:47 AM, Andreas Reichel
>      > <andreas@manticore-projects.com
>     <mailto:andreas@manticore-projects.com>> wrote:
>      >         Dear List,
>      >
>      >         the last day I had a hard time figuring out how to hand over
>      >         timestamps
>      >         using prepared statements.
>      >
>      >         The table looks like this:
>      >
>      >         trader=# \d trader.tickdata
>      >                            Table "trader.tickdata"
>      >               Column       |            Type             | Modifiers
>      >         -------------------+-----------------------------+-----------
>      >          id_instrument     | smallint                    | not null
>      >          id_stock_exchange | smallint                    | not null
>      >          timestamp         | timestamp without time zone | not null
>      >          price             | double precision            | not null
>      >
>      >
>      >         Now I would like to retrieve ticks using a prepared statement
>      >         like this:
>      >
>      >         -- GET TICKDATA
>      >         select
>      >                 t1.id_instrument,
>      >                 t1.id_stock_exchange,
>      >                 t1."timestamp",
>      >                 t1.price,
>      >                 coalesce(t2.quantity,0) quantity
>      >         from
>      >                 trader.tickdata t1
>      >                 left join trader.volumedata t2
>      >                         ON (t1.id_instrument=t2.id_instrument AND
>      >         t1.id_stock_exchange=t2.id_stock_exchange AND
>      >         t1."timestamp"=t2."timestamp")
>      >         where
>      >                 t1.id_instrument= ?
>      >                 AND t1.id_stock_exchange= ?
>      >                 --careful with TIMEZONE here!
>      >                 AND t1."timestamp">= ?
>      >                 AND t1."timestamp"<= ?
>      >         ORDER BY t1."timestamp" ASC;
>      >
>      >         If I hand over java.util.Date or java.sql.Date or
>      >         java.sql.Timestamp the
>      >         query will be executed but returns the wrong number of
>      >         records;
>      >
>      >         However, if I change the query into:
>      >         -- GET TICKDATA
>      >         select
>      >                 t1.id_instrument,
>      >                 t1.id_stock_exchange,
>      >                 t1."timestamp",
>      >                 t1.price,
>      >                 coalesce(t2.quantity,0) quantity
>      >         from
>      >                 trader.tickdata t1
>      >                 left join trader.volumedata t2
>      >                         ON (t1.id_instrument=t2.id_instrument AND
>      >         t1.id_stock_exchange=t2.id_stock_exchange AND
>      >         t1."timestamp"=t2."timestamp")
>      >         where
>      >                 t1.id_instrument= ?
>      >                 AND t1.id_stock_exchange= ?
>      >                 --careful with TIMEZONE here!
>      >                 AND t1."timestamp">= cast(? as timestamp)
>      >                 AND t1."timestamp"<= cast(? as timestamp)
>      >         ORDER BY t1."timestamp" ASC;
>      >
>      >         and hand over a formated date "yyyy-MM-dd HH:mm:ss" it works
>      >         correctly.
>      >         Now I have on simple questions please:
>      >
>      >         What is the correct way to hand over a Java Date parameter
>      >         (avoiding the
>      >         double String manipulation)?
>      >
>      >         Thank you and best regards!
>      >         Andreas
>      >
>      >
>      >
>      >
>      >         --
>      >         Sent via pgsql-jdbc mailing list
>     (pgsql-jdbc@postgresql.org <mailto:pgsql-jdbc@postgresql.org>)
>      >         To make changes to your subscription:
>      > http://www.postgresql.org/mailpref/pgsql-jdbc
>      >
>      >
>
>
>



-- 
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc



^ permalink  raw  reply  [nested|flat] 13+ messages in thread

* Re: Timestamp vs. Java Date/Timestamp
@ 2013-02-12 09:06  Andreas Reichel <andreas@manticore-projects.com>
  parent: Dave Cramer <pg@fastcrypt.com>
  1 sibling, 0 replies; 13+ messages in thread

From: Andreas Reichel @ 2013-02-12 09:06 UTC (permalink / raw)
  To: Dave Cramer <pg@fastcrypt.com>; +Cc: pgsql-jdbc

Hello Dave,

sorry for late response, I was on travel.
The ant test seems to work for me:

[javac] /home/are/Downloads/pgjdbc/build.xml:399: warning:
'includeantruntime' was not set, defaulting to build.sysclasspath=last;
set to false for repeatable builds

runtest:
    [junit] Testsuite: org.postgresql.test.jdbc2.Jdbc2TestSuite
    [junit] Tests run: 298, Failures: 0, Errors: 0, Time elapsed: 25.658
sec
    [junit] 
    [junit] ------------- Standard Error -----------------
    [junit] DatabaseEncodingTest: Skipping UTF8 database tests as test
database encoding is SQL_ASCII
    [junit] ------------- ---------------- ---------------
    [junit] Testsuite:
org.postgresql.test.jdbc2.optional.OptionalTestSuite
    [junit] Tests run: 40, Failures: 0, Errors: 0, Time elapsed: 2.02
sec
    [junit] 
    [junit] Testsuite: org.postgresql.test.jdbc3.Jdbc3TestSuite
    [junit] Tests run: 69, Failures: 0, Errors: 0, Time elapsed: 2.102
sec
    [junit] 
    [junit] Testsuite: org.postgresql.test.xa.XATestSuite
    [junit] Tests run: 0, Failures: 0, Errors: 0, Time elapsed: 0.109
sec
    [junit] 
    [junit] ------------- Standard Output ---------------
    [junit] Skipping XA tests because max_prepared_transactions = 0.
    [junit] ------------- ---------------- ---------------
    [junit] Testsuite: org.postgresql.test.extensions.ExtensionsSuite
    [junit] Tests run: 0, Failures: 0, Errors: 0, Time elapsed: 0.104
sec
    [junit] 
    [junit] Testsuite: org.postgresql.test.jdbc4.Jdbc4TestSuite
    [junit] Tests run: 29, Failures: 3, Errors: 2, Time elapsed: 0.816
sec
    [junit] 
    [junit] Testcase: testSAXRead(org.postgresql.test.jdbc4.XmlTest):
FAILED
    [junit] expected:<[B1B2]> but was:<[]>
    [junit] junit.framework.ComparisonFailure: expected:<[B1B2]> but
was:<[]>
    [junit] 	at
org.postgresql.test.jdbc4.XmlTest.transform(XmlTest.java:119)
    [junit] 	at
org.postgresql.test.jdbc4.XmlTest.testRead(XmlTest.java:135)
    [junit] 	at
org.postgresql.test.jdbc4.XmlTest.testSAXRead(XmlTest.java:147)
    [junit] 
    [junit] 
    [junit] Testcase: testStAXRead(org.postgresql.test.jdbc4.XmlTest):
Caused an ERROR
    [junit] Not supported: javax.xml.transform.stax.StAXSource@742a06be
    [junit] org.apache.xml.dtm.DTMException: Not supported:
javax.xml.transform.stax.StAXSource@742a06be
    [junit] 	at
org.apache.xml.dtm.ref.DTMManagerDefault.getDTM(DTMManagerDefault.java:477)
    [junit] 	at
org.apache.xalan.transformer.TransformerImpl.transform(TransformerImpl.java:699)
    [junit] 	at
org.apache.xalan.transformer.TransformerImpl.transform(TransformerImpl.java:1273)
    [junit] 	at
org.apache.xalan.transformer.TransformerImpl.transform(TransformerImpl.java:1251)
    [junit] 	at
org.postgresql.test.jdbc4.XmlTest.transform(XmlTest.java:118)
    [junit] 	at
org.postgresql.test.jdbc4.XmlTest.testRead(XmlTest.java:129)
    [junit] 	at
org.postgresql.test.jdbc4.XmlTest.testStAXRead(XmlTest.java:152)
    [junit] 
    [junit] 
    [junit] Testcase: testStreamRead(org.postgresql.test.jdbc4.XmlTest):
FAILED
    [junit] expected:<[B1B2]> but was:<[]>
    [junit] junit.framework.ComparisonFailure: expected:<[B1B2]> but
was:<[]>
    [junit] 	at
org.postgresql.test.jdbc4.XmlTest.transform(XmlTest.java:119)
    [junit] 	at
org.postgresql.test.jdbc4.XmlTest.testRead(XmlTest.java:135)
    [junit] 	at
org.postgresql.test.jdbc4.XmlTest.testStreamRead(XmlTest.java:157)
    [junit] 
    [junit] 
    [junit] Testcase: testDomWrite(org.postgresql.test.jdbc4.XmlTest):
FAILED
    [junit] expected:<<[?xml version="1.0"
standalone="no"?><]a><b>1</b><b>2</b></...> but
was:<<[]a><b>1</b><b>2</b></...>
    [junit] junit.framework.ComparisonFailure: expected:<<[?xml
version="1.0" standalone="no"?><]a><b>1</b><b>2</b></...> but
was:<<[]a><b>1</b><b>2</b></...>
    [junit] 	at
org.postgresql.test.jdbc4.XmlTest.testWrite(XmlTest.java:188)
    [junit] 	at
org.postgresql.test.jdbc4.XmlTest.testDomWrite(XmlTest.java:197)
    [junit] 
    [junit] 
    [junit] Testcase: testStAXWrite(org.postgresql.test.jdbc4.XmlTest):
Caused an ERROR
    [junit] Can't transform to a Result of type
javax.xml.transform.stax.StAXResult
    [junit] javax.xml.transform.TransformerException: Can't transform to
a Result of type javax.xml.transform.stax.StAXResult
    [junit] 	at
org.apache.xalan.transformer.TransformerIdentityImpl.createResultContentHandler(TransformerIdentityImpl.java:302)
    [junit] 	at
org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:330)
    [junit] 	at
org.postgresql.test.jdbc4.XmlTest.testWrite(XmlTest.java:171)
    [junit] 	at
org.postgresql.test.jdbc4.XmlTest.testStAXWrite(XmlTest.java:202)
    [junit] 
    [junit] 
    [junit] Test org.postgresql.test.jdbc4.Jdbc4TestSuite FAILED
    [junit] Testsuite: org.postgresql.test.ssl.SslTestSuite
    [junit] Tests run: 0, Failures: 0, Errors: 0, Time elapsed: 0.135
sec
    [junit] 
    [junit] ------------- Standard Output ---------------
    [junit] Skipping ssloff8.
    [junit] Skipping sslhostnossl8.
    [junit] Skipping ssloff9.
    [junit] Skipping sslhostnossl9.
    [junit] Skipping sslhostgh8.
    [junit] Skipping sslhostgh9.
    [junit] Skipping sslhostbh8.
    [junit] Skipping sslhostbh9.
    [junit] Skipping sslhostsslgh8.
    [junit] Skipping sslhostsslgh9.
    [junit] Skipping sslhostsslbh8.
    [junit] Skipping sslhostsslbh9.
    [junit] Skipping sslhostsslcertgh8.
    [junit] Skipping sslhostsslcertgh9.
    [junit] Skipping sslhostsslcertbh8.
    [junit] Skipping sslhostsslcertbh9.
    [junit] Skipping sslcertgh8.
    [junit] Skipping sslcertgh9.
    [junit] Skipping sslcertbh8.
    [junit] Skipping sslcertbh9.
    [junit] ------------- ---------------- ---------------


There are errors but the standard tests seem to work well. What issue
exactly are you referring to please? Which test fails for you?

Best regards
Andreas

On Fri, 2013-02-08 at 09:13 -0500, Dave Cramer wrote:
> 
> Andreas this does not pass the built in tests. run ant test to see 
> 
> Dave Cramer
> 
> dave.cramer(at)credativ(dot)ca
> http://www.credativ.ca
> 
> 
> 
> On Tue, Feb 5, 2013 at 11:11 PM, Andreas Reichel
> <andreas@manticore-projects.com> wrote:
>         Dave,
>         
>         my previous post was not correct, but I finally found the
>         culprit:
>         
>         For any reason we use bindString:
>         
>         bindString(i, connection.getTimestampUtils().toString(cal, d),
>         Oid.UNSPECIFIED);
>         
>         which formats Date into a String, but without information on
>         the time:
>         
>         public synchronized String toString(Calendar cal, Date x) {
>                 if (cal == null)
>                     cal = defaultCal;
>         
>                 cal.setTime(x);
>                 sbuf.setLength(0);
>         
>                 if (x.getTime() == PGStatement.DATE_POSITIVE_INFINITY)
>         {
>                     sbuf.append("infinity");
>                 } else if (x.getTime() ==
>         PGStatement.DATE_NEGATIVE_INFINITY) {
>                     sbuf.append("-infinity");
>                 } else {
>         // the date only but no time
>                     appendDate(sbuf, cal);
>         //
>                     appendEra(sbuf, cal);
>                     appendTimeZone(sbuf, cal);
>                 }
>         
>                 showString("date", cal, x, sbuf.toString());
>         
>                 return sbuf.toString();
>             }
>         
>         When I modified this function into:
>         
>         public synchronized String toString(Calendar cal, Date x) {
>                 if (cal == null)
>                     cal = defaultCal;
>         
>                 cal.setTime(x);
>                 sbuf.setLength(0);
>         
>                 if (x.getTime() == PGStatement.DATE_POSITIVE_INFINITY)
>         {
>                     sbuf.append("infinity");
>                 } else if (x.getTime() ==
>         PGStatement.DATE_NEGATIVE_INFINITY) {
>                     sbuf.append("-infinity");
>                 } else {
>                     appendDate(sbuf, cal);
>         
>         // obey the time too as java.util.Date holds the time
>                     sbuf.append(" ");
>                     appendTime(sbuf, cal, 0);
>         //
>                     appendEra(sbuf, cal);
>                     appendTimeZone(sbuf, cal);
>                 }
>         
>                 showString("date", cal, x, sbuf.toString());
>         
>                 return sbuf.toString();
>             }
>         
>         everything works as expected and also everything else still
>         worked well.
>         (My program uses a lot of date/time conversions so I have some
>         confidence).
>         
>         Now there are two questions please:
>         
>         a) would you like to apply this small change because
>         java.util.Date
>         holds time information so we should obey it
>         
>         b) why is there all this Date/String conversion instead just
>         using
>         millis/Long? I expected using setDate() gives better
>         performance than
>         handing over Strings but now I found that it does exactly the
>         same and
>         in an unexpected way?
>         
>         Best regards
>         Andreas
>         
>         
>         
>         
>         On Tue, 2013-02-05 at 09:42 -0500, Dave Cramer wrote:
>         
>         > Andreas,
>         >
>         >
>         > What are you using to setTimestamp in the prepared
>         statement ? setDate
>         > or setTimestamp ?
>         >
>         > Dave Cramer
>         >
>         > dave.cramer(at)credativ(dot)ca
>         > http://www.credativ.ca
>         >
>         >
>         >
>         > On Tue, Feb 5, 2013 at 12:47 AM, Andreas Reichel
>         > <andreas@manticore-projects.com> wrote:
>         >         Dear List,
>         >
>         >         the last day I had a hard time figuring out how to
>         hand over
>         >         timestamps
>         >         using prepared statements.
>         >
>         >         The table looks like this:
>         >
>         >         trader=# \d trader.tickdata
>         >                            Table "trader.tickdata"
>         >               Column       |            Type             |
>         Modifiers
>         >
>         -------------------+-----------------------------+-----------
>         >          id_instrument     | smallint                    |
>         not null
>         >          id_stock_exchange | smallint                    |
>         not null
>         >          timestamp         | timestamp without time zone |
>         not null
>         >          price             | double precision            |
>         not null
>         >
>         >
>         >         Now I would like to retrieve ticks using a prepared
>         statement
>         >         like this:
>         >
>         >         -- GET TICKDATA
>         >         select
>         >                 t1.id_instrument,
>         >                 t1.id_stock_exchange,
>         >                 t1."timestamp",
>         >                 t1.price,
>         >                 coalesce(t2.quantity,0) quantity
>         >         from
>         >                 trader.tickdata t1
>         >                 left join trader.volumedata t2
>         >                         ON
>         (t1.id_instrument=t2.id_instrument AND
>         >         t1.id_stock_exchange=t2.id_stock_exchange AND
>         >         t1."timestamp"=t2."timestamp")
>         >         where
>         >                 t1.id_instrument= ?
>         >                 AND t1.id_stock_exchange= ?
>         >                 --careful with TIMEZONE here!
>         >                 AND t1."timestamp">= ?
>         >                 AND t1."timestamp"<= ?
>         >         ORDER BY t1."timestamp" ASC;
>         >
>         >         If I hand over java.util.Date or java.sql.Date or
>         >         java.sql.Timestamp the
>         >         query will be executed but returns the wrong number
>         of
>         >         records;
>         >
>         >         However, if I change the query into:
>         >         -- GET TICKDATA
>         >         select
>         >                 t1.id_instrument,
>         >                 t1.id_stock_exchange,
>         >                 t1."timestamp",
>         >                 t1.price,
>         >                 coalesce(t2.quantity,0) quantity
>         >         from
>         >                 trader.tickdata t1
>         >                 left join trader.volumedata t2
>         >                         ON
>         (t1.id_instrument=t2.id_instrument AND
>         >         t1.id_stock_exchange=t2.id_stock_exchange AND
>         >         t1."timestamp"=t2."timestamp")
>         >         where
>         >                 t1.id_instrument= ?
>         >                 AND t1.id_stock_exchange= ?
>         >                 --careful with TIMEZONE here!
>         >                 AND t1."timestamp">= cast(? as timestamp)
>         >                 AND t1."timestamp"<= cast(? as timestamp)
>         >         ORDER BY t1."timestamp" ASC;
>         >
>         >         and hand over a formated date "yyyy-MM-dd HH:mm:ss"
>         it works
>         >         correctly.
>         >         Now I have on simple questions please:
>         >
>         >         What is the correct way to hand over a Java Date
>         parameter
>         >         (avoiding the
>         >         double String manipulation)?
>         >
>         >         Thank you and best regards!
>         >         Andreas
>         >
>         >
>         >
>         >
>         >         --
>         >         Sent via pgsql-jdbc mailing list
>         (pgsql-jdbc@postgresql.org)
>         >         To make changes to your subscription:
>         >         http://www.postgresql.org/mailpref/pgsql-jdbc
>         >
>         >
>         
>         
>         
> 
> 




-- 
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc



^ permalink  raw  reply  [nested|flat] 13+ messages in thread

* Re: Timestamp vs. Java Date/Timestamp
@ 2013-02-13 05:37  Andreas Reichel <andreas@manticore-projects.com>
  parent: Dave Cramer <pg@fastcrypt.com>
  3 siblings, 2 replies; 13+ messages in thread

From: Andreas Reichel @ 2013-02-13 05:37 UTC (permalink / raw)
  To: Dave Cramer <pg@fastcrypt.com>; +Cc: pgsql-jdbc

Dave,

please find a test attached. I guess, I can shed some light on it in the
meantime. 

To me it seems, that setDate()/getDate() indeed ignores any time values
(hh:mm:ss.s) but parses the day-part only (yyyy-mm-dd).
At the same time, setTimestamp()/getTimestamp() behaves correctly.

(Note: in Postgres Date is Date only without Time, while Timestamp obeys
the Time, I was not completely aware of this. I thought the only
difference between Date and Timestamp is Milliseconds vs. Nanoseconds.)

On the same time java.sql.Date and java.util.Date support time
information and in fact you can handover a java.sql.Date parameter to a
Timestamp field.

This is the part when I get confused: the timestamp field holds time
information, the java.sql.Date parameter holds time information -- still
it is cut off in the middle. 


Now I would like to suggest a couple of small changes:
a) allow java.util.Date in setObject() and convert it into
java.sql.Timestamp automatically 
b) keep the time info whenever setting/returning java.sql.Date to/from a
Timestamp field

However, for the moment I am fine as I understood now the need for using
java.sql.Timestamp when working with time.

Thank you a lot and best regards
Andreas

PS: 

-- 
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc

Attachments:

Test.java (text/x-java, 2.8K) download /* * * Copyright (C) 2012 Andreas Reichel <andreas@manticore-projects.com> * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ package com.manticore.database; import java.sql.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.logging.Level; import java.util.logging.Logger; public class Test { public final static Logger logger=Logger.getAnonymousLogger(); public final static SimpleDateFormat sdf=new SimpleDateFormat("YYYY-MM-DD hh:mm:ss.s"); public final static String timestampStr="2013-02-11 21:59:02.0"; public static java.sql.Timestamp getSqlTimestamp(String s) throws ParseException { return new java.sql.Timestamp(sdf.parse(s).getTime()); } public static java.sql.Date getSqlDate(String s) throws ParseException { return new java.sql.Date(sdf.parse(s).getTime()); } public static void main(String[] args) throws ClassNotFoundException, SQLException, ParseException { String sqlStr="create table date_test (date_field timestamp)"; String sqlStr1="insert into date_test values(?)"; String sqlStr2="select date_field from date_test where date_field=?"; Class.forName("org.postgresql.Driver"); Connection conn=null; PreparedStatement prep=null; ResultSet rs=null; try { conn=DriverManager.getConnection("jdbc:postgresql:test", "test", "password"); try { conn.createStatement().executeUpdate(sqlStr); } catch (Exception ex) { logger.log(Level.FINER, "Create Table", ex); } prep=conn.prepareStatement(sqlStr1); prep.setObject(1, getSqlDate(timestampStr)); prep.executeUpdate(); prep=conn.prepareStatement(sqlStr2); prep.setObject(1, getSqlDate(timestampStr)); rs=prep.executeQuery(); if (rs.next()) { boolean valid = 0==rs.getDate(1).compareTo(sdf.parse(timestampStr)); logger.info("found date: " + rs.getDate(1) + " which is " + (valid ? " correct" : " NOT correct ")); } } finally { if (rs!=null) rs.close(); if (prep!=null) prep.close(); if (conn!=null) conn.close(); } } }
^ permalink raw reply [nested|flat] 13+ messages in thread

* Re: Timestamp vs. Java Date/Timestamp
@ 2013-02-13 11:29  Dave Cramer <pg@fastcrypt.com>
  parent: Andreas Reichel <andreas@manticore-projects.com>
  1 sibling, 1 reply; 13+ messages in thread

From: Dave Cramer @ 2013-02-13 11:29 UTC (permalink / raw)
  To: Andreas Reichel <andreas@manticore-projects.com>; +Cc: pgsql-jdbc

On Wed, Feb 13, 2013 at 12:37 AM, Andreas Reichel <
andreas@manticore-projects.com> wrote:

> Dave,
>
> please find a test attached. I guess, I can shed some light on it in the
> meantime.
>
> To me it seems, that setDate()/getDate() indeed ignores any time values
> (hh:mm:ss.s) but parses the day-part only (yyyy-mm-dd).
> At the same time, setTimestamp()/getTimestamp() behaves correctly.
>
> (Note: in Postgres Date is Date only without Time, while Timestamp obeys
> the Time, I was not completely aware of this. I thought the only
> difference between Date and Timestamp is Milliseconds vs. Nanoseconds.)
>
>
And this is the crux of the matter SQL DATE does not have time in it. While
java.sql.Date being derived from java.util.Date does.


> On the same time java.sql.Date and java.util.Date support time
> information and in fact you can handover a java.sql.Date parameter to a
> Timestamp field.
>
> This is the part when I get confused: the timestamp field holds time
> information, the java.sql.Date parameter holds time information -- still
> it is cut off in the middle.
>
>
> Now I would like to suggest a couple of small changes:
> a) allow java.util.Date in setObject() and convert it into
> java.sql.Timestamp automatically
> b) keep the time info whenever setting/returning java.sql.Date to/from a
> Timestamp field
>
> However, for the moment I am fine as I understood now the need for using
> java.sql.Timestamp when working with time.
>
>
And I think that is the way it will remain. I'm afraid this would break way
more than it would fix



Dave Cramer

dave.cramer(at)credativ(dot)ca
http://www.credativ.ca

^ permalink  raw  reply  [nested|flat] 13+ messages in thread

* Re: Timestamp vs. Java Date/Timestamp
@ 2013-02-13 16:13  Thomas Kellerer <spam_eater@gmx.net>
  parent: Andreas Reichel <andreas@manticore-projects.com>
  1 sibling, 0 replies; 13+ messages in thread

From: Thomas Kellerer @ 2013-02-13 16:13 UTC (permalink / raw)
  To: pgsql-jdbc

Andreas Reichel, 13.02.2013 06:37:
> On the same time java.sql.Date and java.util.Date support time
> information and in fact you can handover a java.sql.Date parameter to a
> Timestamp field.

But due to the removing of the time part this will *not* work.

> This is the part when I get confused: the timestamp field holds time
> information, the java.sql.Date parameter holds time information -- still
> it is cut off in the middle.

Yes, that's per documentation.

http://docs.oracle.com/javase/6/docs/api/java/sql/Date.html

"To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date
instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero [...]"

Note the part about "setting ... to zero"

So as soon as you create a java.sql.Date you lose the time information.
  
If you want to be JDBC compliant there are only two simple things to remember:

* use java.sql.Date together with setDate()/getDate() for date columns
* use java.sql.Timestamp together with setTimestamp()/getTimestamp() for timestamp columns

This works across all DBMS that I have worked with
(Oracle is a bit special but in general you should simply treat their DATE as timestamp)

The only problem are columns with timezones as none of the Java classes can deal with that.

Thomas




-- 
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc



^ permalink  raw  reply  [nested|flat] 13+ messages in thread

* Re: Timestamp vs. Java Date/Timestamp
@ 2013-02-13 17:26  dmp <danap@ttc-cmc.net>
  parent: Dave Cramer <pg@fastcrypt.com>
  0 siblings, 0 replies; 13+ messages in thread

From: dmp @ 2013-02-13 17:26 UTC (permalink / raw)
  To: Dave Cramer <pg@fastcrypt.com>; pgsql-jdbc

I agree that more things would break then fix. setDate() should
not be used to fill a PostgreSQL TIMESTAMP data type field.

It is fine to use in the application java.util.Date, but then just
convert it to the TIMESTAMP type for PostgreSQL in setTimeStamp() by
using java.util.Date.getTime(). Insure the format is correct though
with a SimpleDateFormat.

Timestamp With Time Zone, timestamptz, can also be handle exactly the
same way by just using the formatter to include a time zone.

SimpleDateFormat timeStampFormat;
java.sql.Timestamp dateTimeValue;
java.util.Date dateParse;

timeStampFormat = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss z");
dateParse = timeStampFormat.parse("2008-12-30 15:16:08 MST");
dateTimeValue = new java.sql.Timestamp(dateParse.getTime());
prepared_sqlStatement.setTimestamp(i++, dateTimeValue);

danap

Dave Cramer wrote:
> And I think that is the way it will remain. I'm afraid this would break
> way more than it would fix
>
>
>
> Dave Cramer



-- 
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc



^ permalink  raw  reply  [nested|flat] 13+ messages in thread


end of thread, other threads:[~2013-02-13 17:26 UTC | newest]

Thread overview: 13+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2013-02-05 05:47 Timestamp vs. Java Date/Timestamp Andreas Reichel <andreas@manticore-projects.com>
2013-02-05 14:42 ` Dave Cramer <pg@fastcrypt.com>
2013-02-06 02:38   ` Andreas Reichel <andreas@manticore-projects.com>
2013-02-06 03:01   ` Andreas Reichel <andreas@manticore-projects.com>
2013-02-06 04:11   ` Andreas Reichel <andreas@manticore-projects.com>
2013-02-08 14:13     ` Dave Cramer <pg@fastcrypt.com>
2013-02-08 19:09       ` dmp <danap@ttc-cmc.net>
2013-02-12 09:06       ` Andreas Reichel <andreas@manticore-projects.com>
2013-02-13 05:37   ` Andreas Reichel <andreas@manticore-projects.com>
2013-02-13 11:29     ` Dave Cramer <pg@fastcrypt.com>
2013-02-13 17:26       ` dmp <danap@ttc-cmc.net>
2013-02-13 16:13     ` Thomas Kellerer <spam_eater@gmx.net>
2013-02-05 15:07 ` Thomas Kellerer <spam_eater@gmx.net>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox