Postgresql recordset output display in Ruby cucumber - html

I am facing difficulty in displaying postgresql output in ruby and also if there is any way to print the same output in html.
Given below is the code and Error:
Then(/^selecting source table$/) do
require 'pg'
conn = PGconn.connect("localhost",5433,'','', "db", "postgres", "pass")
result = conn.exec('select EMP_ID,DEPT_ID,DEPT_NAME,EMP_NAME from EMP_TABLE')
result.each do |row|
puts row['EMP_ID'] + ' | ' + row['DEPT_ID'] + ' | ' + row['DEPT_NAME'] + ' | ' + row['EMP_NAME']
end
end
ERROR:
NoMethodError: undefined method +' for nil:NilClass
./features/step_definitions/my_steps.rb:45:inblock (2 levels) in ' ./features/step_definitions/my_steps.rb:44:in each'
./features/step_definitions/my_steps.rb:44:in/^selecting source table$/' ./features/PG.feature:12:in `Then selecting source table' 1 scenario (1 failed) 1 step (1 failed) 0m0.072s

One of your row[whatever] values is nil. If you cast everything to a string it should work.
result.each do |row|
puts row['EMP_ID'].to_s + ' | ' + row['DEPT_ID'].to_s + ' | ' + row['DEPT_NAME'].to_s + ' | ' + row['EMP_NAME'].to_s
end
Even better, you can use the .join() method to do that and clean up your logic at the same time.
result.each do |row|
puts row.join(' | ')
end
EDIT!
My bad, that's a hash, not an array. Give me 10 minutes and I'll give you the correct answer...
EDIT 2
Since it's a hash, you need to add the .values method in there.
result.each do |row|
puts row.values.join(' | ')
end

Related

Ignore CSV File header from uploaded CSV file

I am using APEX DATA PARSER for parsing the data from CSV file, while parsing the file the table header also saving to the database. how to remove that?
Source Code:
IF p_table_name = 'Staging_table' THEN
l_columns_item := 'col001,col002,col003,col004,col005,col006'||',col007,col008,col009';
END IF;
l_ddl :=
'insert into '
|| p_table_name
|| ' '
|| 'select '
|| l_columns_item
|| ' '
|| 'from apex_application_temp_files f, '
|| ' table( apex_data_parser.parse(
p_content => f.blob_content,
p_file_name => f.filename ) ) p '
|| 'where f.name ='''
|| p_file_name
|| '''';
The CSV File headers and values are saving to the DB:(Both Header and Values):
CSV Header:
Name - DSR - ID - External_Id - Customer - Created - Date/Time - Request Type - Created By
CSV Values:
ER_120 -1715 - 120 - 1815093826 - TEST CUSTOMER - 8/4/2020 13:35 - TEST QUEUE - XXX
So i want to save only the values. how to remove the csv file header using APEX DATA PARSER?
According to the documentation there is a skip argument, so:
apex_data_parser.parse(
p_content => f.blob_content,
p_file_name => f.filename,
p_skip_rows => 1
)

How do I fix random numbers after they've been generated in access?

I have generated unique pseudorandom numbers for each row which are subject to a particular field (Field1) in a query in Access. They have been successfully generated and I would like to fix them (kind of like copy and pasting as values). I guess my question would be, is this the best way to do this or will they always change as they are being recalculated on the query? I am open to any other suggestions, but once they have been calculated for the first time, I want them to stay as they are and not change again. Thanks!
Here is the current query's SQL:
SELECT [qry_1].*, Rnd([Field1]) AS Random
FROM qry_1;
You don't need a table. You can use a collection:
' Builds random row numbers in a select, append, or create query
' with the option of a initial automatic reset.
'
' Usage (typical select query with random ordering):
' SELECT RandomRowNumber(CStr([ID])) AS RandomRowID, *
' FROM SomeTable
' WHERE (RandomRowNumber(CStr([ID])) <> RandomRowNumber("",True))
' ORDER BY RandomRowNumber(CStr([ID]));
'
' The Where statement shuffles the sequence when the query is run.
'
' Usage (typical select query for a form with random ordering):
' SELECT RandomRowNumber(CStr([ID])) AS RandomRowID, *
' FROM SomeTable
' ORDER BY RandomRowNumber(CStr([ID]));
'
' The RandomRowID values will resist reordering and refiltering of the form.
' The sequence can be shuffled at will from, for example, a button click:
'
' Private Sub ResetRandomButton_Click()
' RandomRowNumber vbNullString, True
' Me.Requery
' End Sub
'
' and erased each time the form is closed:
'
' Private Sub Form_Close()
' RandomRowNumber vbNullString, True
' End Sub
'
' Usage (typical append query, manual reset):
' 1. Reset random counter manually:
' Call RandomRowNumber(vbNullString, True)
' 2. Run query:
' INSERT INTO TempTable ( [RandomRowID] )
' SELECT RandomRowNumber(CStr([ID])) AS RandomRowID, *
' FROM SomeTable;
'
' Usage (typical append query, automatic reset):
' INSERT INTO TempTable ( [RandomRowID] )
' SELECT RandomRowNumber(CStr([ID])) AS RandomRowID, *
' FROM SomeTable
' WHERE (RandomRowNumber("",True)=0);
'
' 2018-09-11. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function RandomRowNumber( _
ByVal Key As String, _
Optional Reset As Boolean) _
As Single
' Error codes.
' This key is already associated with an element of this collection.
Const KeyIsInUse As Long = 457
Static Keys As New Collection
On Error GoTo Err_RandomRowNumber
If Reset = True Then
Set Keys = Nothing
Else
Keys.Add Rnd(-Timer * Keys.Count), Key
End If
RandomRowNumber = Keys(Key)
Exit_RandomRowNumber:
Exit Function
Err_RandomRowNumber:
Select Case Err
Case KeyIsInUse
' Key is present.
Resume Next
Case Else
' Some other error.
Resume Exit_RandomRowNumber
End Select
End Function
It is explained in detail in my article Random Rows in Microsoft Access
(If you have no account, browse to the link: Read the full article).
Full code including a demo is on GitHub: VBA.RowNumbers

Extracting Number From String SQL

I have a normal SQL statement:
SELECT VALUE_ID, UF_CRM_TASK FROM b_uts_tasks_task
Now this returns a a different field everytime but they take the form of the following:
a:1:{i:0;s:7:"CO_2012";} or a:1:{i:0;s:5:"CO_12";} or a:1:{i:0;s:7:"CO_2017";}
Basically they're different everytime. What I need is to just get the number after the CO_ part. I have tried TRIM but because everything changes in the leading and trailing section I don't think this would work.
I have looked on Stack Overflow for a while and cannot find it. I know how to do it in PHP:
$data = $row['UF_CRM_TASK'];
$companyID = substr($data, strpos($data, "CO_") + 1);
$newCompanyID = preg_replace('/[^0-9.]+/', '', $companyID);
But not SQL. Thanks in advance
In MYSQL is a bit ugly:
/*SUBSTRING_INDEX BASED ON CO_ AND THE LAST " - in 2 SUBSTRINGS*/
SELECT `VALUE_ID`, SUBSTRING_INDEX(SUBSTRING_INDEX(`UF_CRM_TASK`, 'CO_', -1), '"', 1) AS `COMPANY_ID` FROM `b_uts_tasks_task`
In PHP you can just unserialize():
$data = unserialize($row['UF_CRM_TASK']);
$companyID = str_replace('CO_', '', $data[0]);
eg:
$data = unserialize('a:1:{i:0;s:5:"CO_12";}');
echo str_replace('CO_', '', $data[0]);
//==> 12
You need to use CharIndex and SubString (Microsoft SQL) or
This is the sample code I made for my Microsoft SQL server:
declare #companyIdString varchar(50) = 'a:1:{i:0;s:7:"CO_2012";}'
print 'Company ID in a string: ' + #companyIdString
print 'Find first position: ' + Cast(charindex('"CO_', #companyIdString) as varchar(2))
print 'Locate the second position (the last "): ' + Cast(charindex('"', #companyIdString, charindex('"CO_', #companyIdString)+4) as varchar(2))
print 'Extracted Company Id: ' + substring(#companyIdString,charindex('"CO_', #companyIdString)+4, charindex('"', #companyIdString, charindex('"CO_', #companyIdString)+4) - charindex('"CO_', #companyIdString) - 4)
select
#companyIdString as CompanyIdString,
substring(#companyIdString,charindex('"CO_', #companyIdString)+4, charindex('"', #companyIdString, charindex('"CO_', #companyIdString)+4) - charindex('"CO_', #companyIdString) - 4) as CompanyId
I also made the same code on a mySQL server:
set #companyIdString := 'a:1:{i:0;s:7:"CO_2012";}';
select
#companyIdString as CompanyIdString,
substring_index(substring_index(substring_index(#companyIdString, '"', 2), '"', -1), '_', -1) as CompanyId
The substring_index starts by locating the second " (string is now a:1:{i:0;s:7:"CO_2012), then it searches backward with the -1 to locate the first " (string is now CO_2012). And then it searches backward for the underscore (string is now 2012).

Parameterizing an SQL query which uses the NOT LIKE, " ^ " wildcard?

How can I parameterize the following query? (By the way I'm using a full text indexed table, hence the CONTAINS())
SELECT * FROM Table WHERE CONTAINS(Column, 'cat OR dog')
and ((column NOT LIKE '%[^ cat OR dog]%'));
This didn't work:
DECLARE #term1 VARCHAR(10);
DECLARE #term2 VARCHAR(10);
SET #term1 = 'cat';
SET #term2 = 'dog';
SET #term3 = #term1 + ' ' + 'OR' + ' ' + #term2;
SET #term4 = '[^ #term1 OR #term2 ]' ;
SELECT * FROM table WHERE CONTAINS(column, #term3) <--up to this point works
AND (column NOT LIKE '%[#term4]%'); <--this part doesn't include the second term (#term2)
If you'd like to fiddle with this on your end, my Full Text Indexed table looks like:
animalListID AnimalsList
1 cat dog
2 cat
3 cat dog bird
(basically i need the parameterized version of the SELECT statement which returns the rows with 'cat dog' and 'cat' and NOT 'cat dog bird')
**This is a VERY oversimplified version of my data, but the question is an exact match of the concept I'm trying to achieve. The table will have millions of rows, and many terms in each row.
You should do
SET #term4 = '[^ ' + #term1 + ' OR ' + #term2 + ' ]';
and
column NOT LIKE '%' + #term4 + '%'
Alternatively, you could initialize #term4 to also include the % signs:
SET #term4 = '%[^ ' + #term1 + ' OR ' + #term2 + ' ]%';
and then simplify the LIKE statement to:
column NOT LIKE #term4

MSSQL to MYSQL using CASE WHEN THEN SUBSTRING & CHARINDEX

I am having some real difficulty converting the below MSSQL statement to produce the same results in MYSQL.
The MSSQL query is as follows:
SELECT Radius_AdslUser.Password, Radius_AdslIp.IpAdd, Route =
CASE WHEN Radius_AdslIP.Route IS NULL
THEN NULL
WHEN Radius_AdslIp.TotalIp = 8
THEN Radius_AdslIP.Ipadd + '/29 ' + SUBSTRING(Radius_AdslIp.Route, 10, Charindex(' ', Radius_AdslIp.Route) - 10) + ' 1'
WHEN Radius_AdslIp.TotalIp = 4
THEN Radius_AdslIP.Ipadd + '/30 ' + SUBSTRING(Radius_AdslIp.Route, 10, Charindex(' ', Radius_AdslIp.Route) - 10) + ' 1'
WHEN Radius_AdslIp.TotalIp = 16
THEN Radius_AdslIP.Ipadd + '/28 ' + SUBSTRING(Radius_AdslIp.Route, 10, Charindex(' ', Radius_AdslIp.Route) - 10) + ' 1'
END, AVPair =
CASE WHEN Radius_AdslUser.bandcap IS NULL
THEN NULL
ELSE 'throttle=' + Radius_AdslUser.bandcap
END, Radius_AdslIp.Subnet
FROM Radius_AdslUser,Radius_AdslIp
WHERE Username = 'username#test.tld'
AND Suspended = 0
AND Radius_AdslUser.IpAddId = Radius_AdslIp.IpAddId
Which produces the following result:
Password IpAdd Route AVPair Subnet
kmbjdatr 10.0.0.1 10.0.0.1/29 10.0.0.0 1 NULL 255.255.255.255
The format of the tables are as follows:
Radius_AdslIp
IpAddId IpAdd Subnet TotalIp UsableIp Route TypeId
944 10.0.0.1 255.255.255.255 8 6 ip:route=10.0.0.0 255.255.255.248 4
Radius_AdslUser
Username Password IpAddId
username#test.tld kmbjdatr 944
I have substituted CHARINDEX for LOCATE and have used CONCAT but am not having much luck.
For example:
WHEN Radius_AdslIp.TotalIp = 8 THEN Radius_AdslIp.Ipadd = CONCAT(Radius_AdslIp.Ipadd, '/29 ')
The table formats in MYSQL are identical.
Any help would be greatly appreciated.
Seems like you are not applying the CONCAT function correctly. Basically, a SQL Server expression like this:
column_name + 'constant string' + function_call() + #variable
would look like this in MySQL:
CONCAT(column_name, 'constant string', function_call(), #variable)
The particular wrong part in your excerpt seems to be Radius_AdslIp.Ipadd = (the one before CONCAT). Not sure what you meant by that, but in any event it's just not needed there.