PYTHON - Using double quotes in SQL constant - sql

I have a SQL query entered into a constant. One of the fields that I need to put in my where clause is USER which is a key word. To run the query I put the keyword into double quotes.
I have tried all of the suggestions from here yet none seem to be working.
Here is what I have for my constant:
SELECT_USER_SECURITY = "SELECT * FROM USER_SECURITY_TRANSLATED WHERE \"USER\" = '{user}' and COMPANY = " \
"'company_number' and TYPE NOT IN (1, 4)"
I am not sure how to get this query to work from my constant.
I also tried wrapping the whole query in """. I am getting a key error on the USER.
SELECT_USER_SECURITY = """SELECT * FROM USER_SECURITY_TRANSLATED WHERE "USER" = '{user}' and
COMPANY = 'company_number' and TYPE NOT IN (1, 4)"""
Below is the error I am getting:
nose.proxy.KeyError: 'user'

So the triple quoted solution was the best one. The problem I was running into was I had not included the "user" key in my dictionary of params which formatted the query.

Related

Fetching attribute from JSON string with JSON_VAL cause "<attribute> is invalid in the used context" error

A proprietary third-party application stores JSON strings in it's database like this one:
{"state":"complete","timestamp":1614776473000}
I need the timestamp and found out that
DB2 offers JSON functions. Since it's stored as string in the PROF_VALUE column, I guess that converting with SYSTOOLS.JSON2BSON is required, before I can use JSON_VAL to fetch the timestamp:
SELECT SYSTOOLS.JSON_VAL(SYSTOOLS.JSON2BSON(PROF_VALUE), "timestamp", "f")
FROM EMPINST.PROFILE_EXTENSIONS ext
WHERE PROF_PROPERTY_ID = 'touchpointState'
This causes an error that timestamp is invalid in the used context ( SQLCODE=-206, SQLSTATE=42703, DRIVER=4.26.14). The same error is thown when I remove the JSON2BSON call like this
SELECT SYSTOOLS.JSON_VAL(PROF_VALUE, "timestamp", "f")
Also not working with the same error (different data-types):
SELECT SYSTOOLS.JSON_VAL(SYSTOOLS.JSON2BSON(PROF_VALUE), "state", "s:1000")
SELECT SYSTOOLS.JSON_VAL(PROF_VALUE) "state", "s:1000")
I don't understand this error. My syntax is like the documented JSON_VAL ( json-value , search-string , result-type) and it is the same like in the examples, where they show how to fetch the name field of an object.
I also played around a bit with JSON_TABLE to use raw input data for testing (instead of the database data), but it seems not suiteable for that.
SELECT *
FROM TABLE(SYSTOOLS.JSON_TABLE( SYSTOOLS.JSON2BSON('{"state":"complete","timestamp":1614776473000}'), 'state','s:32')) DATA
This gave me a table with one row: Type = 2 and Value = complete.
I had two problems in my query: First it seems that double quotes " are for object references. I wasn't aware that there is any difference, because in most databases I used yet, both single ' and double quotes " are equal.
The second problem is, that JSON_VAL needs to be called without SYSTOOLS, but the reference is still needed on SYSTOOLS.JSON2BSON(PROF_VALUE).
With those changes, the following query worked:
SELECT JSON_VAL(SYSTOOLS.JSON2BSON(PROF_VALUE), 'timestamp', 'f')
FROM EMPINST.PROFILE_EXTENSIONS ext
WHERE PROF_PROPERTY_ID = 'touchpointState'

how to insert an array of strings to sql query in ruby

I have this query in ruby:
sql = "SELECT variants.id,
code,
regular_price,
price_before_sale
FROM variants
WHERE variants.code IN (#{context.codes.join(",")})"
where context.codes = ['PRDCT-1','PRDCT-2']
now context.codes becomes (PRDCT1,PRDCT2) inside the sql query because of the .join but what I want to happen is ('PRDCT1','PRDCT2') what am I missing?
EDI: I have tried to do (#{context.codes.join("','")}) but it returns (PRDCT1','PRDCT2)
Don't do that. Bobby Tables is watching. Instead, provide the adequate number of placeholders:
sql = "SELECT variants.id,
code,
regular_price,
price_before_sale
FROM variants
WHERE variants.code IN (#{context.codes.map { "?" }.join(",")})"
and then provide *context.codes in statement parameters.
I got it.
I added single quotes to ('#{context.codes.join("','")}')

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...
}

Active record query failed - Escape quote from query

Background
Framework: Codeignighter/PyroCMS
I have a DB that stores a list of products, I have a duplicate function in my application that first looks for the common product name so it can add a 'suffix' value to the duplicated product.
Code in my Products model class
$product = $this->get($id);
$count = $this->db->like('name', $product->name)->get('products')->num_rows();
$new_product->name = $product->name . ' - ' . $count;
On the second line the application fails only when the $product->name contains quotes.
I was with the understanding that Codeignighter escaped all strings so I dont know why I get this error.
So I tried to use MySQL escape string function but that didn't help either.
The Error Message
A Database Error Occurred
Error Number: 1064
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 's Book%'' at line 3
SELECT * FROM `products` WHERE `name` LIKE '%Harry\\'s Book%'
var_dump
Below is the output of doing a var_dump on product->name before and after the line in question;
string 'Harry's Book' (length=12)
A Database Error Occurred
Error Number: 1064
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 's Book%'' at line 3
SELECT * FROM `products` WHERE `name` LIKE '%Harry\\'s Book%'
Let's do some testing about this.
Here is what you are doing
$count = $this->db->like('name', $product->name)->get('products')->num_rows();
And i suspect $product->name contains this.
Harry's Book
As we know this is coming from the database table as you are using.
Where you are using the upper query mentioned it is wrapping it with
single quotes and producing this result.
SELECT * FROM `products` WHERE `name` LIKE '%Harry\\'s Book%'
As you see it is escaping apostrophy to tell it is not end of string
Therefore escaping it with two slashes.One for apostrophy and one for being in single quote.
What you have to do is
Before assigning the parameter to query wrap it with double quotes.
$product_name = "$product->name";
And now pass it to query.
$count = $this->db->like('name', $product_name)->get('products')->num_rows();
The output will be this
SELECT * FROM `products` WHERE `name` LIKE '%Harry\'s Book%'
You see the differece here. It contains single slash now and the record will
be found.
Other answers didn't work for me, this does though:
$count = $this->db->query("SELECT * FROM `default_firesale_products` WHERE `title` LIKE '".addslashes($product['title'])."'")->num_rows();
Whenever CI Active Record mangles your queries you can always just put a raw query in instead and have full control.
Try this, using stripslashes() around $product->name:
$count = $this->db->like('name', stripslashes($product->name))->get('products')->num_rows();
CI automatically escapes characters with active records but I bet that it's already escaped if you entered it previously via active record in CI. So now it is doing a double escape.
Update: You may also want to try adding the following before you query:
$this->db->_protect_identifiers = FALSE;
Last try: try querying this way since it seems like the like active record is causing the error:
$like = $product->name;
$this->db->query("SELECT * FROM `products` WHERE `name` LIKE '%$like%'");

Playframework SQL query

Im trying to make a query that help me get a user by its username. What i want to do is to check if the given username is unique. so what i thought about is to uppercase the username when i do my select request and compare it with an uppercase of the given username. This is what i tried:
SQL("select * from utilisateur where upper(pseudo) = {pseudo}").on(
'pseudo -> pseudo.toUpperCase
).as(Utilisateur.utilisateur.singleOpt)
but it get this error:
[RuntimeException: SqlMappingError(too many rows when expecting a single one)]
I tried this too:
SQL("select * from utilisateur where ucase(pseudo) = {pseudo}").on(
'pseudo -> pseudo.toUpperCase
).as(Utilisateur.utilisateur.singleOpt)
and i got this error:
[PSQLException: ERROR: function ucase(character varying) does not exist Indice : No function matches the given name and argument types. You might need to add explicit type casts. Position : 33]
What should i do ?
PS:Im using PostgreSQL 9.1
First, in Play!, only use singleOpt if you're expecting exactly one row back. Otherwise, it will throw an exception. Since you do want just one row, add a LIMIT 1 to the end of your query.
The PostgreSQL function you want is upper(). Here's an example:
SQL("select * from utilisateur where upper(pseudo) = {pseudo} limit 1").on(
'pseudo -> pseudo.toUpperCase
).as(Utilisateur.utilisateur.singleOpt)
(You can play with it here: http://sqlfiddle.com/#!1/6226c/5)