In my project, I am using Postgres database, but sometimes, for development, I am using H2. I am trying to define an sql script which will update a timestamp column as described below, but I could not find a single format that can be applied both to Postgres and a to H2.
Basically, the sql is trying to set the timestamp to be NOW + 1 week
.
Here is the sql that works for Postgres:
update mytable set mytime = CURRENT_TIMESTAMP + INTERVAL '7 days';
Here is the sql that works for H2:
update mytable set mytime = CURRENT_TIMESTAMP + 7;
Can someone suggest an single sql that can do the same for both databases?
H2 tries to emulate PostgreSQL syntax and support a few features and extensions. It'll never be a full match for PostgreSQL's behaviour, and doesn't support all features. The only options you have are: Use PostgreSQL in testing; or.
PostgreSQL is an advanced, enterprise class open source relational database that supports both SQL (relational) and JSON (non-relational) querying.
PostgreSQL is a powerful, open source object-relational database system that uses and extends the SQL language combined with many features that safely store and scale the most complicated data workloads.
We ran into a similar issue where we use PostgreSQL for our app, but our unit tests use H2. We ended up just moving the date arithmetic into the application code. So, using the example above, the sql was change to be
update mytable set mytime = ?;
And then in the application code (using Java) we figured out the time:
Instant future1Week = Instant.now().plus(1, ChronoUnit.WEEKS);
And bound that value in the PreparedStatement.
According to my test, this works for both H2 and PostgreSQL:
update mytable set mytime =
cast(cast(current_timestamp as date) + 7 as timestamp) +
cast(current_timestamp as time);
It is a bit strange I agree, but it is the only way I found with current versions of H2 and PostgreSQL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With