Doctrine triple quotes sql alias - sql

I have following sql error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'a.`role`' in 'field list'
My doctrine select is
$query->select('a.role AS role');
When i look on the symfony error i see that doctrine makes the 'a.role' to a.role.
Here the full SQL Statement =
at Doctrine_Connection->execute('SELECT `a`.```role``` AS `a__0`, `a`.`role` AS `a__0` FROM `offer` `o` INNER JOIN `account` `a` *******)

It is best practice to not even use backticks. The only time they are necessary is when you are using tables that are reserved words, and it is suggested you don't do that in the first place.
Turn off quoting by using the quote_identifier attribute in your databases.yml. An example of the output is referenced here.
Example databases.yml:
default:
class: sfDoctrineDatabase
param:
dsn: mysql:dbname=database_name;host=localhost
username: username
password: password
attributes:
quote_identifier: false
use_native_enum: false
validate: all
default_table_charset: utf8
default_table_collate: utf8_general_ci

Related

Prisma PostgreSQL queryRaw error code 42P01 table does not exist

I am trying to run a query that searches items in the Item table by how similar their title and description are to a value, the query is the following:
let items = await prisma.$queryRaw`SELECT * FROM item WHERE SIMILARITY(name, ${search}) > 0.4 OR SIMILARITY(description, ${search}) > 0.4;`
However when the code is run I receive the following error:
error - PrismaClientKnownRequestError:
Invalid `prisma.$queryRaw()` invocation:
Raw query failed. Code: `42P01`. Message: `table "item" does not exist`
code: 'P2010',
clientVersion: '4.3.1',
meta: { code: '42P01', message: 'table "item" does not exist' },
page: '/api/marketplace/search'
}
I have run also the following query:
let tables = await prisma.$queryRaw`SELECT * FROM pg_catalog.pg_tables;`
Which correctly shows that the Item table exists! Where is the error?
After doing some light research, It looks like you possibly need double-quotes. Try
let items = await prisma.$queryRaw`SELECT * FROM "Item" ... blah blah
I say this because PostgreSQL tables names and columns default to lowercase when not double-quoted. If you haven't built much of your db, it may be worth wild to make all the tables and columns lowercase so that you won't have to keep adding double quotes and escaping characters.
References:
PostgreSQL support
Are PostgreSQL columns case sensitive?

PostgreSQL - Query nested json in text column

My situation is the following
-> The table A has a column named informations whose type is text
-> Inside the informations column is stored a JSON string (but is still a string), like this:
{
"key": "value",
"meta": {
"inner_key": "inner_value"
}
}
I'm trying to query this table by seraching its informations.meta.inner_key column with the given query:
SELECT * FROM A WHERE (informations::json#>>'{meta, inner_key}' = 'inner_value')
But I'm getting the following error:
ERROR: invalid input syntax for type json
DETAIL: The input string ended unexpectedly.
CONTEXT: JSON data, line 1:
SQL state: 22P02
I've built the query following the given link: DevHints - PostgreSQL
Does anyone know how to properly build the query ?
EDIT 1:
I solved with this workaround, but I think there are better solutions to the problem
WITH temporary_table as (SELECT A.informations::json#>>'{meta, inner_key}' as inner_key FROM A)
SELECT * FROM temporary_table WHERE inner_key = 'inner_value'

Postgres | V9.4 | Extract value from json

I have a table that one of the columns is in type TEXT and holds a json object inside.
I what to reach a key inside that json and ask about it's value.
The column name is json_representation and the json looks like that:
{
"additionalInfo": {
"dbSources": [{
"user": "Mike"
}]
}
}
I want to get the value of the "user" and ask if it is equal to "Mike".
I tried the following:
select
json_representation->'additionalInfo'->'dbSources'->>'user' as singleUser
from users
where singleUser = 'Mike';
I keep getting an error:
Query execution failed
Reason:
SQL Error [42883]: ERROR: operator does not exist: text -> unknown
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
Position: 31
please advice
Thanks
The error message tells you what to do: you might need to add an explicit type cast:
And as you can not reference a column alias in the WHERE clause, you need to wrap it into a derived table:
select *
from (
select json_representation::json ->'additionalInfo'->'dbSources' -> 0 ->>'user' as single_user
from users
) as t
where t.single_user = 'Mike';
:: is Postgres' cast operator
But the better solution would be to change the column's data type to json permanently. And once you upgrade to a supported version of Postgres, you should use jsonb.

ruby on rails prepared statement for oracle view/function

I have the following code which executes an oracle view as follows:
def run_query
connection.exec_query(
"SELECT * FROM TABLE(FN_REQRESP(#{type_param},
#{search_type_param},
#{tid_param},
#{last_param},
#{key_param},
#{tran_id_param},
#{num_param},
#{start_date_param},
#{end_date_param}))")
end
The output of the above query is as follows:
SELECT * FROM TABLE(FN_REQRESP('ALL',
'ALL_TRAN',
'100007',
'',
'',
'',
'',
TO_DATE('27-January-2017','dd-MON-yy'),
TO_DATE('31-January-2017','dd-MON-yy')))
The problem is that above query has a SQL injection vulnerability.
So, i tried to add a prepare statement as follows:
connection.exec_query('SELECT * FROM TABLE(FN_REQRESP(?,?,?,?,?,?,?,?,?))','myquery',[type_param,search_type_param,tid_param,last_param,key_param,tran_id_param,num_param,start_date_param,end_date_param])
I get the following error now:
NoMethodError: undefined method `type' for "'ALL'":String: SELECT *
FROM TABLE(FN_REQRESP(?,?,?,?,?,?,?,?,?))
It's the single quotes that messing it up I beleive. Is there a way to overcome this?
EDIT:
I tried NDN's answer and the error below:
OCIError: ORA-00907: missing right parenthesis: SELECT * FROM TABLE(FN_REQRESP('\'ALL\'',
'\'ALL_TRAN\'',
'\'100007\'',
'\'\'',
'\'\'',
'\'\'',
'\'\'',
'TO_DATE(\'01-February-2017\',\'dd-MON-yy\')',
'TO_DATE(\'10-February-2017\',\'dd-MON-yy\')'))
Looking at the source, binds gets cast in some magical way and you have to pass a named prepare: true argument as well.
It also used to work differently in older versions.
To save yourself the trouble, you can simply use #sanitize:
params = {
type: type_param,
search_type: search_type_param,
tid: tid_param,
last: last_param,
key: key_param,
tran_id: tran_id_param,
num: num_param,
start_date: start_date_param,
end_date: end_date_param,
}
params.each do |key, param|
params[key] = ActiveRecord::Base.sanitize(param)
end
connection.exec_query(
"SELECT * FROM TABLE(FN_REQRESP(#{params[:type]},
#{params[:search_type]},
#{params[:tid]},
#{params[:last]},
#{params[:key]},
#{params[:tran_id]},
#{params[:num]},
#{params[:start_date]},
#{params[:end_date]}))"
)
This is called Prepared Statement. In doc you can find an example how to use it.

PYTHON - Using double quotes in SQL constant

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.