JSON Parser Has Issue With Sql Syntax But Query Works - sql

To start, I had this error:
Error parsing data org.json.JSONException: Value You of type java.lang.String cannot be converted to JSONObject
After some searching, I found a potential solution using substring to see if there were just some phantom characters causing an issue: 'json.substring(3)'
After trying different substring amounts, I got to json.substring(36) and it finally showed me more than 5 letters at a time:
Error parsing data org.json.JSONException: Expected literal value at character 0 of ; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AND from_user = 277976949048048 AND (status = 'pending' OR status = 'accepted'))' at line 2
Maybe this new 'expected literal' thing is caused by doing the substring 36, but either way, it seems like there is an issue with my SQL syntax even though I tested it directly with the server and it works perfectly. here is my sql query.
$result = mysql_query("SELECT status FROM users join requests on users.facebook_id=requests.from_user
WHERE (to_user = $id AND from_user = $fbid AND (status = 'pending' OR status = 'accepted'))
OR (from_user = $id AND to_user = $fbid AND (status = 'pending' OR status = 'accepted'))
LIMIT 1") or die(mysql_error());
Any help much appreciated because now I'm officially stumped.

I had some issues in the past with parsing JSON files including huge integer numbers.
The number 277976949048048 seems too large to be treated as an integer, I would suggest treating it as a string.

Related

Apache Calcite Fails to Parse Its Own Google BigQuery Output

I'm new to Apache Calcite and am running into a strange "gap" - given a simple select query:
select * from orders
I parse it using:
SqlParser.Config sqlParserConfig = SqlParser
.configBuilder()
.setConformance(SqlConformanceEnum.LENIENT)
.build();
SqlParser parser = SqlParser.create(sqlQuery, sqlParserConfig);
SqlNode parseAst = parser.parseQuery();
CalciteCatalogReader catalogReader = buildCatalogReader(schema, typeFactory);
SqlValidator.Config validatorConf = SqlValidator.Config.DEFAULT.withSqlConformance(SqlConformanceEnum.BIG_QUERY);
validatorConf = validatorConf.withIdentifierExpansion(true);
SqlValidator validator = SqlValidatorUtil.newValidator(SqlStdOperatorTable.instance(),
catalogReader, typeFactory,
validatorConf)
validator.validate(parseAst).toSqlString(BigQuerySqlDialect.DEFAULT).toString();
Which results in:
SELECT ORDERS.o_orderkey, ORDERS.o_custkey, ORDERS.o_orderstatus, ORDERS.o_totalprice, ORDERS.`o_order date`, ORDERS.o_orderpriority, ORDERS.o_clerk, ORDERS.o_shippriority, ORDERS.o_comment
FROM ORDERS AS ORDERS
(reasonable, note the quoted identifier for `o_order date`, necessary due to whitespace in columnname)
If I then take that query string and pass it back through (setting conformance to SqlConformanceEnum.BIG_QUERY) the parse fails with:
org.apache.calcite.sql.parser.SqlParseException: Lexical error at line 1, column 95. Encountered: "`" (96), after : ""
Puzzling on face, I tried again with a parse config:
SqlParser.Config sqlParserConfig = SqlParser
.configBuilder()
.setConformance(getConformance(SqlConformanceEnum.BIG_QUERY))
.setQuoting(Quoting.BACK_TICK_BACKSLASH)
.build();
to force handling backtick-quoted identifiers and I up with:
SELECT ORDERS.o_orderkey AS O_ORDERKEY, ORDERS.o_custkey AS O_CUSTKEY, ORDERS.o_orderstatus AS O_ORDERSTATUS, ORDERS.o_totalprice AS O_TOTALPRICE, ORDERS.`o_order date`, ORDERS.o_orderpriority AS O_ORDERPRIORITY, ORDERS.o_clerk AS O_CLERK, ORDERS.o_shippriority AS O_SHIPPRIORITY, ORDERS.o_comment AS O_COMMENT
FROM ORDERS AS ORDERS
which is usable... but
why is the "default" conformance for BigQuery setting DOUBLE_QUOTE when bigquery uses backticks
why does loop-parsing lead to a different query than on the input? (running the aliased query back through a second time gets itself back, so it does stabilize, but the initial inconsistency is weird

How to fix error "Conversion failed when converting datetime from character string" in SQL Query?

The error that I found at the log is the one below.
'Illuminate\Database\QueryException' with message 'SQLSTATE[22007]:
[Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Conversion
failed when converting date and/or time from character string. (SQL:
SELECT COUNT(*) AS aggregate
FROM [mytable]
WHERE [mytable].[deleted_at] IS NULL
AND [created_at] BETWEEN '2015-09-30T00:00:00' AND '2015-09-30T23:59:59'
AND ((SELECT COUNT(*) FROM [mytable_translation]
WHERE [mytable_translation].[item_id] = [mytable].[id]) >= 1)
)'
in
wwwroot\myproject\vendor\laravel\framework\src\Illuminate\Database\Connection.php:625
On the database, the DataType is datetime and is not null
Based on marc_s's answer I tried to change the format that I'm sending to the database. So I tried without the T on and [created_at] between '2015-09-30 00:00:00' and '2015-09-30 23:59:59'.
In my local, I'm using mysql, and the code works just fine. If I test the query above on the SQL Server client, both (with and without the T) works too.
How can I fix this problem without create any changes on the database itself?
The PHP/Laravel code:
$items = $items->whereBetween($key, ["'".$value_aux."T00:00:00'", "'".$value_aux."T23:59:59'"]);
With #lad2025 help, I got it to work.
Based on the point of his comments on my question, I changed in the code part (Laravel/PHP in this case) the format that I was passing. (In reality, I "removed" the format it self, and just added fields to a variable before passing to the query. This way, I let the database decide the format that he wants)
Instead of
$itens = $itens->whereBetween($key, ["'".$value_aux."T00:00:00'", "'".$value_aux."T23:59:59'"]);
I changed the code to this:
$sta = $value_aux."T00:00:00";
$end = $value_aux."T23:59:59";
$itens = $itens->whereBetween($key, [$sta, $end]);

Multiple parameter values

I have a problem with BIRT when I try to pass multiple values from report parameter.
I'm using BIRT 2.6.2 and eclipse.
I'm trying to put multiple values from cascading parameter group last parameter "JDSuser". The parameter is allowed to have multiple values and I'm using list box.
In order to be able to do that I'm writing my sql query with where-in statement where I replace text with javascript. Otherwise BIRT sql can't get multiple values from report parameter.
My sql query is
select jamacomment.createdDate, jamacomment.scopeId,
jamacomment.commentText, jamacomment.documentId,
jamacomment.highlightQuote, jamacomment.organizationId,
jamacomment.userId,
organization.id, organization.name,
userbase.id, userbase.firstName, userbase.lastName,
userbase.organization, userbase.userName,
document.id, document.name, document.description,
user_role.userId, user_role.roleId,
role.id, role.name
from jamacomment jamacomment left join
userbase on userbase.id=jamacomment.userId
left join organization on
organization.id=jamacomment.organizationId
left join document on
document.id=jamacomment.documentId
left join user_role on
user_role.userId=userbase.id
right join role on
role.id=user_role.roleId
where jamacomment.scopeId=11
and role.name in ( 'sample grupa' )
and userbase.userName in ( 'sample' )
and my javascript code for that dataset on beforeOpen state is:
if( params["JDSuser"].value[0] != "(All Users)" ){
this.queryText=this.queryText.replaceAll('sample grupa', params["JDSgroup"]);
var users = params["JDSuser"];
//var userquery = "'";
var userquery = userquery + users.join("', '");
//userquery = userquery + "'";
this.queryText=this.queryText.replaceAll('sample', userquery);
}
I tryed many different quote variations, with this one I get no error messages, but if I choose 1 value, I get no data from database, but if I choose at least 2 values, I get the last chosen value data.
If I uncomment one of those additional quote script lines, then I get syntax error like this:
The following items have errors:
Table (id = 597):
+ An exception occurred during processing. Please see the following message for details: Failed to prepare the query execution for the
data set: Organization Cannot get the result set metadata.
org.eclipse.birt.report.data.oda.jdbc.JDBCException: SQL statement does not return a ResultSet object. SQL error #1:You have an error in
your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'rudolfs.sviklis',
'sample' )' at line 25 ;
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near
'rudolfs.sviklis', 'sample' )' at line 25
Also, I should tell you that i'm doing this by looking from working example. Everything is the same, the previous code resulted to the same syntax error, I changed it to this script which does the same.
The example is available here:
http://developer.actuate.com/community/forum/index.php?/files/file/593-default-value-all-with-multi-select-parsmeter/
If someone could give me at least a clue to what I should do that would be great.
You should always use the value property of a parameter, i.e.:
var users = params["JDSuser"].value;
It is not necessary to surround "userquery" with quotes because these quotes are already put in the SQL query arround 'sample'. Furthermore there is a mistake because userquery is not yet defined at line:
var userquery = userquery + users.join("', '");
This might introduce a string such "null" in your query. Therefore remove all references to userquery variable, just use this expression at the end:
this.queryText=this.queryText.replaceAll('sample', users.join("','"));
Notice i removed the blank space in the join expression. Finally once it works finely, you probably need to make your report input more robust by testing if the value is null:
if( params["JDSuser"].value!=null && params["JDSuser"].value[0] != "(All Users)" ){
//Do stuff...
}

Hibernate createSQLQuery and Toad SQL query return different results - parameter problems?

I'm a newbie at Hibernate so excuse me if some of this is glaringly obvious but it's been a very, very long day. I am trying to create and execute a simple query in Hibernate and Toad/Oracle.
The Toad/Oracle sql reads:
select
count(*)
from
fpps_owner.fee_claim_payment_lines l,
fpps_owner.fee_claim_payments p
where
l.fee_claim_payment_id = p.fee_claim_payment_id and
p.claim_index = 87167895
The above returns 10 records, which is correct
The following Java code returns 0 records, which is NOT correct
String sLinesAvailable =
"select count(*) from " +
"fpps_owner.fee_claim_payment_lines l, fpps_owner.fee_claim_payments p " +
"where " +
"l.fee_claim_payment_id = p.fee_claim_payment_id and p.claim_index = :id";
Query qLinesAvailable = em.createNativeQuery(sLinesAvailable);
qLinesAvailable.setParameter("id", "87167895"); // fails
qLinesAvailable.setParameter("id", 87167895); // fails
List<Object> out = (List<Object>) qLinesAvailable.getResultList();
BigDecimal x = (BigDecimal) out.get(0);
Returns 0 records. Using .getSingleResult() also returns 0 records.
What am I missing here?
Any help would be GREATLY appreciated!
If you are not seeing any malformed query errors, it seems like the parameter is not binding correctly.
To debug, I'd print out that SQL statement the line after you set the parameter. This is the only way you can see the SQL after the parameter is set in order to compare it with Toad.
What does your binding file look like? Maybe you have a different name in there for the ID, so it's not able to find it based on the name. Trying binding with the parameter's order value, just as a test.
This might give some ideas: http://www.mkyong.com/hibernate/hibernate-parameter-binding-examples/
Best of luck! We've all been there :)
What happens when you try:
(Number) query.getSingleResult();
Your query isn't returning a list, but rather just a count.
Good luck.

There was an error parsing the query. [ Token line number = 1

First of all, I'm new to the club and must say I find it a very interesting site, and it has really helped me a lot with my coding experiences in C#. Thanks for that.
On a total different note, I'm getting the follow error at one of our customers (we resell document management software). And I'm trying to determine if this error message as stated below can cause performance issues.
Google'ing this error message has already informed me that it can be caused when using Reserved Words as Column Names.
24-4-2012 11:16:49 [ERROR] :There was an error parsing the query. [
Token line number = 1,Token line offset = 77,Token in error = 66667 ]
UPDATE WS_LOCATION SET Frequency = #FreqParams, LUTime =
#LUTimeParams, Client = '', Matter = '' WHERE WSLoc_ID = '22' occured
on InsertIntoLocationTables.
I'm not very familiar with all of the Reserved Words in SQL, perhaps any of you can help me out with determining what is the cause of this error?
It's a local SQL Compact database bytheway (.sdf).
Enclosing your names with brackets will prevent the error of using T-SQL reserved words.
UPDATE [WS_LOCATION] SET
[Frequency] = #FreqParams,
[LUTime] = #LUTimeParams,
[Client] = '',
[Matter] = ''
WHERE [WSLoc_ID] = '22';
If you have a problem with reserved words, prefix your column names with the table name :
UPDATE WS_LOCATION
SET WS_LOCATION.Frequency = #FreqParams, WS_LOCATION.LUTime = #LUTimeParams, WS_LOCATION.Client = '', WS_LOCATION.Matter = ''
WHERE WS_LOCATION.WSLoc_ID = '22'