Zend 2 escaping single-quote - zend-framework2

I am using Zend Framework 2 to generate the following escaped single-quote SQL query,
SELECT
`document`.*
FROM
`document`
WHERE
(
`document`.`document_taxon` LIKE '%Men\'s Health %' --escaped quote
AND `document`.`document_source_id` = ' 5 '
AND `document`.`document_published` = ' 1 '
AND `document`.`document_deleted` = ' 0 '
)
ORDER BY
`document_id` DESC
LIMIT 25 OFFSET 0
But I am getting this instead,
SELECT
`document`.*
FROM
`document`
WHERE
(
`document`.`document_taxon` LIKE '%Men's Health%'
AND `document`.`document_source_id` = ' 5 '
AND `document`.`document_published` = ' 1 '
AND `document`.`document_deleted` = ' 0 '
)
ORDER BY
`document_id` DESC
LIMIT 25 OFFSET 0
And here is my code
class DocumentTable extends TableGateway
{
....
$select=$this->getSql()->select();
$select->columns(array('*'));
$select->where
->NEST
->like('document_taxon', '%' . $label . '%')
->and
->equalTo('document_source_id', $sourceId)
->and
->equalTo('document_published', true)
->and
->equalTo('document_deleted', 0)
->UNNEST;
$select->order('document_id DESC');
$select->limit($limit);
$select->offset($offset);
...
}
I tried,
$this->getAdapter()->getPlatform()->quoteValue($string)
\Zend\Db\Sql\Expression("%". $label . "%")
str_replace("'", "\'", $label)
But I didn’t have much luck. I welcome any suggestion to solve this issue.

I worked it out. I was passing a normalized “label” value instead of the raw value. The above code snippet works fine.

Related

How to pass multiple OR and AND condition in Activate Record in Rails as a string

I'm new in Ruby on rails and I would like to fetch records based on a condition, and I'm passing the condition in a string format. Moreover, I will pass the query in multiple OR and AND conditions. However, right now, I'm stuck that how to pass the query in string format in rails
I have attached the screenshot
#data= CustomAttribute.includes(:custom_attribute_values).where(id: 18, company_id: current_user.company_id).first
The above line executed successfully and gave the output
<CustomAttribute id: 18, data_type: "string", label: "Marital status", code: "marital_status", entity_type: "member", company_id: 1, created_at: "2021-03-10 10:16:15", updated_at: "2021-03-10 10:16:27", is_active: true, is_default: false, rank: nil, is_identifier: false>
but when I executed the below line it gave me the error that
#data.custom_attribute_values.where("\""+"value_string"+"\""+"="+"\""+'Single'+"\"").size
ERROR: column "Single" does not exist
the Single is the value which I would like to count
Here is my code for the dynamic query creation
logical_operator = 'OR'
#custom_attribute = CustomAttribute.includes(:custom_attribute_values).where(id: custom_attribute_ids, company_id: current_user.company_id)
query=""
#custom_attribute.each_with_index do |attribute_object, index|
filter_object= filter_params[:filters].find {|x| x['custom_attribute_id']==attribute_object['id']}
if filter_object.present?
query += "("+ '"' +'value_'+attribute_object.data_type + '"' + ' ' + filter_object['operator'] + ' ' + "'" + filter_object['value'].to_s + "'"+ ")"
end
if index != #custom_attribute.length-1
query+=' '+logical_operator+' '
end
if index == #custom_attribute.length-1
query="'" + " ( " + query + " ) " + "'"
end
end
byebug
puts(#custom_attribute.first.custom_attribute_values.where(query).size)
Any time you're doing a lot of escaping and string addition in Ruby you're doing it wrong. If we clean up how you build your SQL:
"\""+"value_string"+"\""+"="+"\""+'Single'+"\""
things will be clearer. First, put space around your operators for readability:
"\"" + "value_string" + "\"" + "=" + "\"" + 'Single' + "\""
Next, don't use double quotes unless you need them for escape codes (such as \n) or interpolation:
'"' + 'value_string' + '"' + '=' + '"' + 'Single' + '"'
Now we see that we're adding several constant strings so there's no need to add them at all, a single string literal will do:
'"value_string" = "Single"'
Standard SQL uses double quotes for identifiers (such as table and column names) and single quotes for strings. So your query is asking for all rows where the value_string column equals the Single column and there's your error.
You want to use single quotes for the string (and %q(...) to quote the whole thing to avoid adding escapes back in):
#data.custom_attribute_values.where(
%q("value_string" = 'Single')
)
Or better, let ActiveRecord build the query:
# With a positional placeholder:
#data.custom_attribute_values.where('value_string = ?', 'Single')
# Or a named placeholder:
#data.custom_attribute_values.where('value_string = :s', s: 'Single')
# Or most idiomatic:
#data.custom_attribute_values.where(value_string: 'Single')

Dynamic Sql Error , Invalid syntax near '>'

I have the below dynamic sql statement and I'm getting the "Incorrect syntax near '>'. error message. I can not figure out what the problem is, not sure if I'm missing a tick mark or not. I've tried to add extra tick marks and nothing seems to work.
Declare #filters varchar(max)
SET #filters = 'Where PaymentAmount > 0'
BEGIN
SET #filters = #filters + ' AND CONVERT(DATE, AccountingDate) >= '''+ cast #BeginDate as nvarchar) + ''''
SET #filters = #filters + ' AND CONVERT(DATE, AccountingDate) <= '''+ cast(#EndDate as nvarchar) + ''''
END
SET #SQLString = 'Select
,[ReturnDate]
,[PolicyNumber]
From dbo.Bil_ReturnsRepository' + #filters
EXEC(#SQLString)
You need another space before you concat #filters to #SQLString.
SET #SQLString = 'Select
,[ReturnDate]
,[PolicyNumber]
From dbo.Bil_ReturnsRepository ' + #filters
Otherwise the generated sql would be
...
From dbo.Bil_ReturnsRepositoryWhere PaymentAmount > 0
...

Passing in variables to SQL Server stored procedure, where clause

I am writing an application responsible for archiving data and we have the configuration in a database table
Id | TableName | ColumnName | RetentionAmountInDays
1 | DeviceData | MetricTime | 3
So when faced with this configuration, I should archive all data in the DeviceData table where the MetricTime value is before 3 days ago.
The reason I am doing this dynamically is the table names and column names differ (there would be multiple rows)
For each configuration this stored procedure is called
CREATE PROCEDURE GetDynamicDataForArchive
#TableName nvarchar(100),
#ColumnName nvarchar(100),
#OlderThanDate datetime2(7)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql nvarchar(1000);
SET #sql = 'SELECT * FROM ' + #TableName + ' WHERE ' + #ColumnName + ' < #OlderThanDate';
exec sp_executesql #sql;
END
And an example exec line
exec dbo.GetDynamicDataForArchive 'DeviceData', 'MetricTime', '2017-04-16 20:29:29.647'
This results in:
Conversion failed when converting date and/or time from character string.
So something is up with how I am passing in the datetime2 or how I am forming the where clause.
Replace this statement:
SET #sql = 'SELECT * FROM ' + #TableName + ' WHERE ' + #ColumnName + ' < #OlderThanDate'
by
SET #sql = 'SELECT * FROM ' + #TableName + ' WHERE [' + #ColumnName + '] < ''' + cast(#OlderThanDate as varchar(23)) + '''';
I don't particularly like having to convert the datetime to a varchar value though, perhaps there is a better way to do this(?).

SQL Server CE - IMAGE column

I know that IMAGE datatype is deprecated since a while, but for my project I don't have the choice.
The question is: can I have several IMAGE columns in a table in SQL Server CE?
Because when I make an insert (ADO in Delphi) with more than 1 IMAGE column, my program hangs when I call ExecSQL().
With just one IMAGE column, it works:
HSLmySQL.ADOQuery1.SQL.Clear();
HSLmySQL.ADOQuery1.SQL.Add( 'INSERT INTO ' + CONFIG_Table_Name + ' SET ' +
CONFIG_Table[ aCONFIG_PARAM ] + '=' + ':param_blob'; + ' ;' );
HSLmySQL.ADOQuery1.Parameters.ParamByName('param_blob').LoadFromStream( Mstream1, ftBlob );
HSLmySQL.ADOQuery1.ExecSQL();
But with more than one IMAGE column:
HSLmySQL.ADOQuery1.SQL.Clear();
HSLmySQL.ADOQuery1.SQL.Add( 'INSERT INTO ' + CONFIG_Table_Name + ' SET ' +
CONFIG_Table[ aCONFIG_PARAM ] + '=' + ':param_blob', +
CONFIG_Table[ aCONFIG_SCHEDULES ] + '=' + ':schedules_blob'; + '
;' );
HSLmySQL.ADOQuery1.Parameters.ParamByName('param_blob').LoadFromStream( Mstream1, ftBlob );
HSLmySQL.ADOQuery1.Parameters.ParamByName('schedules_blob').LoadFromStream( Mstream2, ftBlob );
HSLmySQL.ADOQuery1.ExecSQL(); // => Boom, no exceptions catch nothing ..
and my program hangs.

Rails - String concatenation issue while processing an array

I am trying to process the results of an array into a string to pass for a search. I want to build a string from the array that would look something like
("categories.name like '%Forms%' or categories.name like '%Apples%'")
serialize :category, JSON
if category.count > 1 && category.index != 0
$search_global.category.each do |cat_name|
cat_name.slice '" '
# cat_name
$array_count = $array_count + 1
if cat_name != ''
$inside_count = $inside_count +1
$cat_name_2 = "categories.name like %" + $cat_name_2 + cat_name + "% or " + $inside_count.to_s
end
end
end
If I select one item, it works fine as in
categories.name like %Forms% or 1
Please note that I am including the inside count just to get a better idea of what is happening.
The problem I have is when I select 2 or more items. categories.name like % is repeated twice and then the array items or listed as in
categories.name like %categories.name like %Calendar% or 1Forms% or 2
I can't seem to figure out why the concatenation isn't working as I expected.
$cat_name_2 = "categories.name like %" + $cat_name_2 + cat_name + "% or " + $inside_count.to_s
Your are using $cat_name_2 as the asignee as well as inside the assignment statement.

Resources