PostgreSql + Query Statement having \r in between the attributes ! - ruby-on-rails

Suppose we have a textarea in which we put example string. Textbox contain :
Earth is revolving around the Sun.
But at the time of saving, I just pressed a enter key after "the sun". Now the statements in texbox ::
Earth is revolving around
the Sun
Now, in database where enter was pressed the \r is stored. Now i am trying to fetch the data but unable, because my query is of such type ::
SELECT * FROM "volume_factors" WHERE lower(volume_notes) like E'atest\\r\\n 100'
Actual data stored in database field
atest\r
100
Please suggest me to solve the issue.I have tried gsub to replace but no change.
search_text_array[1] = search_text_array[1].gsub('\\r\\n','\r\n')
Thanks in Advance !!!

Try this:
update volume_factors set volume_notes = regexp_replace(volume_notes, '\r\n', ' ');
That's to replace crlf with one space for data that is already in the database. You use postgresql's psql to do this.
To prevent new data containing crlf entering database, you should do it in the application. If you use ruby's gsub, do not use single quote, use double quote to recognize \n like this:
thestring.gsub("\n", " ")

Here we can replace \r\n by % to fetch the data.
Seaching Query will be like this ::
SELECT * FROM "volume_factors" WHERE lower(volume_notes) like E'atest% 100'
gsub function ::
search_text_array[1] = search_text_array[1].gsub('\\r\\n','%')

Related

Rails query to substitute field and query

could someone please help me to write a query to substitute hyphens in rails DB field with space?
For eg:
If I have a field called 'name' in a table User having a value 'asdc-sd bc', and want to remove special characters like '-' and replace it with space to match with a given name 'asdc sd bc'.
I tried using lower to convert the name to lowercase but am not able to find out how to substitute the hyphens with space. Please help!
You can use SQL REPLACE function to replace - with spaces(' ').
For example, if you are querying on name column of User model, you can write your query like below:
query_str = 'asdc sd bc'
User.where("REPLACE(name, '-', ' ') = ?", query_str)

Adding special characters in sqlplus

In SQLPlus, how do I add string that contains a special character to my database? The special character I am trying to use is 'é'.
I've tried Aim(atl+130) which is: Aimé but returns 'Aim?'
I copied your character and did this to find the value 233:
select dump('é') from dual;
So you should be able to do this and get it back (of course you can INSERT it too):
select 'Aim' || chr(233) from dual;

How to aggregate multiple rows into one in CSV?

I have following problem:
I have a CSV file, which looks like this:
1,12
1,15
1,18
2,10
2,11
3,20
And I would like to parse it somehow to get this:
1,12,15,18
2,10,11
3,20
Do you have any solution? Thanks!
Here is one solution for you.
This first part just sets up the example for testing. I am assuming you already have a file with values in the second part of the script.
$path = "$env:TEMP\csv.txt"
$data =#"
1,12
1,15
1,18
2,10
2,11
3,20
"#
$data | Set-Content $path
This should be all you need:
$path = "$env:TEMP\csv.txt"
$results = #{}
foreach($line in (Get-Content $path))
{
$split = $line -split ','
$rowid = $split[0]
$data = $split[1]
if(-not($results.$rowid))
{
$results.$rowid = $rowid
}
$results.$rowid += "," + $data
}
$results.values | Sort-Object
Your original dataset does not need to be sorted for this one to work. I slice the data up and insert it into a hashtable.
I don't know your exact code requirement. I will try to write some logic which may help you!
CSV means a text file which I can read into a string or an array
If one will look at the above CSV data, there is a common pattern i.e. after each pair there is a space in-between.
So my parsing will be depending on 2 phases
parse with ' ' i.e. single space and will insert into an array (say elements)
then parse with ',' i.e. comma from each element of elements and save into another array (say details) where odd indexes will be containing the left hand values and even indexes will be containing the right hand values.
So next while printing or using skip the odd index if you have an existing value.
Hope this helps...
Satyaranjan,
thanks for your answer! To clarify - I don't have any code requirements, I can use any language to achieve results. The point is to take unique values from first position (1,2,3) and put all related numbers on the right (1 - 12, 15 and 18 etc.). It is something like GROUP_CONCAT function in MySQL - but unfortunately I don't have such a function, so I am looking for some workaround.
Hope it is more clear now. Thanks

Escaping apostrophe in Ruby

I am trying to escape a single quote in a ruby string. I am using this string as a insert query to push data into the postgresql.
The query that will be generated looks something like this:-
str = insert into table field1,field2 values 'Gaurav's', 'Scooter'
I tried escaping it with
str.gsub("/'/",\\\\')
But this didn't work.
The error that I always get is:
Syntax Error Near s:
I guess i would need a regex to escape single quote inside the two single quotes not sure though.
How do I fix this? Thank you.
You should used prepared statements. Prepared statements help increase your speed. The query is parsed once by the DB. They also help you avoid having to do manual escaping as you are trying to do.
f1_val = "Gaurav's"
f2_val = "Scooter"
# conn is your connection object
conn.prepare('givethisqueryaname', "INSERT INTO table field1,field2 VALUES ($1,$2)")
conn.exec_prepared('givethisqueryaname',[f1_val, f2_val])
If you are given the field names, and field values as a string, then you can do this.
fieldStr = "field1,field2"
valuesStr = "Gaurav's, Scooter"
arr = valuesStr.split(",")
conn.prepare('insert_x', "INSERT INTO table #{fieldStr} VALUES ($1,$2)")
conn.exec_prepared('insert_x', arr)
This works if the single quote you want to escape always is in front of a "s"
1.9.3p125 :020 > str = "insert into table field1,field2 values 'Gaurav's', 'Scooter'"
=> "insert into table field1,field2 values 'Gaurav's', 'Scooter'"
1.9.3p125 :021 > str.gsub("'s","-s")
=> "insert into table field1,field2 values 'Gaurav-s', 'Scooter'"
You can user the difference between single quotes(') and double quotes(").

PostgreSql + Searching Issue for "'" present in string

Here, I have a problem in searching record in Postgresql DB in RoR Application. Name of table :: address_books, name of attributes :: organization_name, federal_tax_id, city, zip , business_name. In search, organization name contain :: Claire's Inc as record. At the time of searching, it does not show the data while we select Claire's Inc in search box. Because "'" breaks the string and gives no result. So I have used "?" replace "'" at time of search in mysql and it works. But I am getting appropriate conversion to make search of this words.
Query :: SELECT * FROM "address_books"
WHERE ( address_books.organization_name = 'Claire?s Inc'
and address_books.federal_tax_id = '59-0940416'
and address_books.city = 'Hoffman Estates'
and address_books.zip = '60192' and address_books.business_name ='' )
ORDER BY address_books.organization_name , city LIMIT 100
Please suggest any other way to make successful search.
Thanks in Advance
You're messing up your data to deal with a matter of query syntax. Put a correctly escaped apostrophe in the place where the apostrophe should be.
One way is to escape it to 'Claire''s Inc'. Another is to use a library that lets you pass parameters and handles the escaping for you. Another is to enter the string as $$Claire's Inc$$ though that syntax allows for other things that may not be appropriate here.
I think you can use RoR parameter substituion, than RoR will escape your dangerous strings for you. something like:
AddressBook.find(:all, :conditions => { "organization_name => ?", "Claire's Inc" })
or
AddressBook.find(:all, :conditions => { :organization_name => "Claire's Inc" })

Resources