Postgres Exception - Internal Statement is right but Query Fails - postgresql

I'm inserting a record into my DB using the following:
PreparedStatement stmt = null;
Connection conn = null;
HashMap<String, Object> hoursMap = new HashMap<String, Object>();
hoursMap.put("PLACE_ID", hours.getPlaceID());
hoursMap.put("DAY", hours.getDayID());
hoursMap.put("TIME_OPEN", hours.getTimeOpen());
hoursMap.put("TIME_CLOSE", hours.getTimeClose());
String insertStr = StatementCreator.insertQueryGenerator("HOURS",
hoursMap);
try {
conn = ConnectionManager.getConnection();
stmt = StatementCreator.createStatement(conn, insertStr, hoursMap,
false);
returnVal = stmt.execute();
ConnectionManager.closeStatement(stmt);
System.out.println("Created");
} catch (SQLException e) {
System.out.println("ERROR");
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
return returnVal;
}
However, when running this I get the following error:
org.postgresql.util.PSQLException: ERROR: column "TIME_OPEN" is of
type time with time zone but expression is of type character varying
Hint: You will need to rewrite or cast the expression. Position: 71
What I can't figure out is why? The reason I say that is if I go into debug mode and look at the internal prepared statement I see the following:
INSERT INTO "HOURS" ("TIME_OPEN","DAY","TIME_CLOSE","PLACE_ID")VALUES('11:30:00-0400',6,'23:59:59-0400',541)
I copy/paste this into my SQL Editor and it runs and inserts the record.
Is there something I'm missing?

There is a subtle but decisive difference between a string literal and a variable of type varchar.
A string literal like '11:30:00-0400' has no type assigned to it. But your function obviously returns varchar, which is the same as '11:30:00-0400'::varchar.
Like the error message informs, you need to add an explicit cast in this case:
'11:30:00-0400'::varchar::timetz
Or, in your case probably:
hours.getTimeOpen())::timetz
(Not sure about the kind of syntax you use.)
Or have your function return the proper type to begin with.
Don't use timetz
As an aside, I would strongly advice against using time with timezone (timetz for short) at all. It's a logically broken type. Postgres only provides it for standard compatibility but advices against its use. I quote the manual here:
To address these difficulties, we recommend using date/time types that
contain both date and time when using time zones. We do not recommend
using the type time with time zone (though it is supported by
PostgreSQL for legacy applications and for compliance with the SQL standard)
And here:
The type time with time zone is defined by the SQL standard, but the
definition exhibits properties which lead to questionable usefulness.
In most cases, a combination of date, time, timestamp without time zone, and timestamp with time zone should provide a complete range of
date/time functionality required by any application.

If you only store the time+timezone, without the date part, you should declare the data type at PostgreSQL's side as timetz (or time with time zone) not timestamptz (or timestamp with time zone).

Related

Changing dd/mm/yyyy/ hh/mm/ss format to yyyymm in Hive

I'm using Hive at the moment. I have a column (column A) of strings which is in the following format 11/9/2009 0:00:00. I'd like to extract the yyyymm. i.e. I'd like the above string to be 200909. I've tried two different methods none of them worked.
I have tried to convert the string using two different methods
concat(year(Column A),lpad(month(Column A),2,0))
convert(datetime, Column A)
For the first row of code I'm receiving : NULL in all rows
For the second one I'm receiving :
Encountered: DATETIME Expected: ALL, CASE, CAST, DEFAULT, DISTINCT,
EXISTS, FALSE, IF, INTERVAL, NOT, NULL, REPLACE, TRUNCATE, TRUE,
IDENTIFIER CAUSED BY: Exception: Syntax error
Use unix_timestamp(string date, string pattern) to convert given date format to seconds passed from 1970-01-01. Then use from_unixtime() to convert to required format:
select from_unixtime(unix_timestamp( '11/9/2009 0:00:00','dd/MM/yyyy HH:mm:ss'), 'yyyyMM');
Result:
200909
Read also: Impala data and time functions and Hive date functions.
One more solution, works in Hive:
select concat(regexp_extract('11/9/2009 0:00:00','(\\d{1,2})/(\\d{1,2})/(\\d{4})',3),lpad(regexp_extract('11/9/2009 0:00:00','(\\d{1,2})/(\\d{1,2})/(\\d{4})',2),2,0))
Since I'm trying to turn strings into YYYYMM I have to use the below, which worked for me:
'concat(substr(Column A, instr(Column A, ' ')-4, 4),substr(Column A, instr(Column A, ' /')+1, 2))'

SSRS Date parameter - foreign language issue

I have a client in Germany using an SSRS report and the date parameter is showing "OKT" instead we need it to be "OCT" for october
Is there a setting to make sure GETDATE() is already converted or will a convert function work?
here is my error:
library!ReportServer_0-45!1554!10/15/2018-10:23:17:: i INFO:
RenderForNewSession('/Finance/MC Dashboard')
processing!ReportServer_0-45!10bc!10/15/2018-10:23:17:: e ERROR:
Throwing
Microsoft.ReportingServices.ReportProcessing.ReportProcessingException:
,
Microsoft.ReportingServices.ReportProcessing.ReportProcessingException:
Query execution failed for dataset 'JournalEntries'. --->
Microsoft.AnalysisServices.AdomdClient.AdomdErrorResponseException:
Query (5, 39) Cannot convert value 'Okt 14, 2018' of type Text to type
Date. at
Microsoft.AnalysisServices.AdomdClient.AdomdConnection.XmlaClientProvider.Microsoft.AnalysisServices.AdomdClient.IExecuteProvider.ExecuteTabular(CommandBehavior
behavior, ICommandContentProvider contentProvider,
AdomdPropertyCollection commandProperties, IDataParameterCollection
parameters)
Since the GetDate is coming through in German from the server, then the SQL CONVERT function should also use German to convert it to a date.
CONVERT(DATETIME, GETDATE(), 106)
If you do get an error, you might need to set the language first (SET Language German;) - though that would be wonky that one SQL function would work in German but the other doesn't.
just capture the data first in a text box and check its format. Depending on how it looks you can worse case convert this receive input param to internal varchar and then just get the date part out. i.e.
declare #internal_param as varchar(15);
set #internal_param = #Input_dateParam --your variable name here
--select logic here

momentjs: Get invalid date when trying to get current date with moment()

Hi Im using firefox and CoffeeScript in an app, I want to get current date with momentjs using default method moment() however when I debug the code I seeinvalid Date, it is very weird, this is my code:
questionStarts =
started_at: moment()
running: true
Then later in my code I create another object and add the property
answer = {}
answer.started_at = questionStarts.started_at
But when I check answer.started_at I get back Invalid date any idea?
Moment has an alternate constructor for strange dates. Since I can't see the value of answer.started_at in your code, I can only guess about how to solve your problem.
Consider for example some strange date format like 08.16.2015 00:00:00. Trying to construct a moment object from it will give the same error you have, Invalid date. That's what happens if you tried constructing my example like this:
//this doesn't work, throws Invalid date message
var ex = moment('08.16.2015 00:00:00');
So, to fix my problem, I give another constructor that informs Moment of the strange date format.
//this does work, however
var ex = moment('08.16.2015 00:00:00', 'MM.DD.YYYY hh:mm:ss');
Now, I can use ex as a typical moment object taking advantage of moment's other methods such as format() diff() and isBetween().

Problems with query using timespan

I am doing a manual query to my postgresql database (using OrmLiteReadConnectionExtensions.SqlList<T>) that has a TimeSpan argument.
SericeStack.Ormlite is converting TimeSpan to ::time instead of ::interval as I would expect it.
More specifically: TimeSpan.FromDays(3) is converted to ((E'00:00:00.000000')::time)(taken form pg logs).
Is there a work around for this?
My current work-around is to use the C# string.Format for this problematic parameter instead of the safe and recommended™ #paramname supported by SqlList<T>.
This could be considered dangerous, but since the parameter is a double, I'm probably Okay.
The relevant part of the string is:
string.Format(CultureInfo.InvariantCulture, "RESTOFTHEQUERY ('{0:0.####} seconds'::interval) RESTOFTHEQUERY", timespan.TotalSeconds);
Don't forget to use CultureInfo.InvariantCulture.
For what it's worth, you can just cast a time value to interval. Demo
SELECT now()::time::interval
So append ::interval in your manual query and you should be fine - except for intervals > 24 hours of course.

Compare dates with Spring Data neo4j

When querying for relationships on a java.util.Date property, what syntax should I use? I tried just using a query like (this is just an example to show what I'm trying to do, so please don't pay attention to variable names there):
#Query("start n1=node({0}) match n1-[r:TYPE]->n2 where r.dateCreated>={1} return r")
Page<Relationship> findAll(Node node, long date, Pageable pager);
But it throws the following error:
Caused by: Don't know how to compare that. Left: 1339845862883; Right: 1339827156836
at org.neo4j.cypher.internal.Comparer$class.compareValuesOfDifferentTypes(Comparer.scala:45)
at org.neo4j.cypher.internal.Comparer$class.compare(Comparer.scala:67)
at org.neo4j.cypher.commands.ComparablePredicate.compare(ComparablePredicate.scala:30)
at org.neo4j.cypher.commands.ComparablePredicate.isMatch(ComparablePredicate.scala:41)
at org.neo4j.cypher.internal.pipes.matching.PatternMatcher$$anonfun$isMatchSoFar$1.apply(PatternMatcher.scala:148)
at org.neo4j.cypher.internal.pipes.matching.PatternMatcher$$anonfun$isMatchSoFar$1.apply(PatternMatcher.scala:148)
I also tried by passing a Date but it just throws the same error but trying to compare a Long and a Date.
I am using spring-data-neo4j version 2.0.1.RELEASE
So the date property's long value is stored as a string in the graph (in newer versions of SDN you can define a #GraphProperty(targetType=long.class) on date fields.
So comparison will work if you pass in the parameter value as String.valueOf(longValue)