ruby variable inside sql statement - sql

I am trying to use a ruby variable inside an sql statement. The following code works and deletes the second record of the templates table. How do i replace this number with my user defined variable "deleteid"?
deleteid = gets.chomp
$db.execute %q{DELETE FROM templates
WHERE id = 2}

You can use string interpolation:
$db.execute %{DELETE FROM templates WHERE id = #{deleteid}}
$db.execute %Q{DELETE FROM templates WHERE id = #{deleteid}}
UPDATE
User can pass arbitrary string. Using deleteid directly can be dangerous. As #muistooshort commented, you should escape the deleteid.
Consult your db driver's documentation for methods that accepts parameter and escape the parameter (or prepare method).
For example, if you use sqlite3-ruby, you can use Database#query, which will escape for you.
$db.prepare(%q{DELETE FROM templates WHERE id = ?}, [deleteid])
in pg, use Connection#exec_params:
$db.exec_params(%q{DELETE FROM templates WHERE id = $1}, [deleteid])

Related

How to use placeholders in JSON (RedBeanPHP)?

I have a task: to check if $username has upvoted the record with the identifier $id. To do this, I need to check that in the JSON array, which is in the "votes" cell, the "upvote" field contains the username (i.e. $username). So I wrote this code (PostgreSQL DB):
$foo = R::getRow('SELECT "votes"::jsonb #> \'{"upvote":[":username"]}\'::jsonb AS "is_upvoted" FROM "pages" WHERE "id" = :id', [":id"=>$id,":username"=>$username];
The problem is that RedBeanPHP, when substituting placeholders, wraps them in single brackets, but PostgreSQL requires me to wrap the names of fields / values ​​of a JSON array in double quotes.
So how can I make it so that RB does not wrap placeholders with single quotes? Or how to make placeholders wrap with double quotes?
There was no need to compose JSON manually and fill in placeholders in it via RB.
It was necessary to create an array with the structure of the required JSON, and use a ready-made array / variable to fill it.
Here's how I did it:
$username_in_array = array('upvote' => array($username));
$username_in_json = json_encode($username_in_array);
$is_upvoted = R::getRow('SELECT "votes"::jsonb #> :username::jsonb AS "is_upvoted" FROM "pages" WHERE "id" = :id', [":id"=>$id,":username"=>$username_in_json];
The request takes the following form:
SELECT "votes"::jsonb #> '{"upvote":["admin"]}'::jsonb AS "is_upvoted" FROM "pages" WHERE "id" = 1
I checked - it works!

How to pass variable to groovy code in Intellij IDEA live templates groovy script?

I have a groovyScript in my Intellij IDEA live template, like this :
groovyScript("D:/test.groovy","", v1)
on my D:/test.groovy i have a code like this:
if ( v1 == 'abc') {
'abc'
}
Now I want to pass v1 variable into test.groovy ,can any one help me how can I do this?
For exemplification purposes I made a live template which is printing a comment with the current class and current method.
This is how my live template is defined:
And here is how I edited the variableResolvedWithGroovyScript variable:
The Expression for the given variable has the follwing value:
groovyScript("return \"// Current Class:\" + _1 + \". Current Method:\"+ _2 ", className(),methodName())
As you can see, in this case the _1(which acts like a variable in the groovy script) takes the value of the first parameter which is the class name, and the _2 takes the value of the
second parameter which is the method name. If another parameter is needed the _3 will be used in the groovy script to reference the given parameter.
The arguments to groovyScript macro are bound to script variables named _1, _2 etc. This is also described at groovyScript help at Edit Template Variables Dialog / Live Template Variables.
I found a solution.
I was needing to calculate a CRC32 of the qualified class name using live models
I used it like this:
groovyScript("
def crc = new java.util.zip.CRC32().with { update _1.bytes; value };
return Long.toHexString(crc);
", qualifiedClassName())
then the result is
Based on the documentation, your variables are available as _1, _2, etc. Please note that variables are passed without dollar signs (so only v1 instead of $v1$)
So your test script should look like
if ( _2 == 'abc') {
'abc'
}

How to evaluate parameter variable stored in a file in jMeter?

Say, I have a jMeter variable var equals 123.
I also have a query stored in a sql file:
SELECT * FROM Table WHERE ID = ${var}
All I need is to read that query from the file and evaluate ${var} into actual value, and then execute it in JDBC Sampler. So I need to combine these two pieces into
SELECT * FROM Table WHERE ID = 123
and pass the query to JDBC sampler.
Though, jMeter doesn't evaluate the ${var} parameter stored in that sql file and all I can pass to JDBC sampler is (obvious one):
SELECT * FROM Table WHERE ID = ${var}.
Does anyone know how to make jMeter evaluate the stored variable into actual value?
I had a similar requirement.
You need to use Beanshell Preprocessor for the JDBC sampler. Copy the below script and put it in a .bsh file and call it. I assumed you have the query stored in 'SQLQuery' variable.
I tested the below script and it works.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String regex = "\\$\\{([^}]+)\\}";
SQLQuery = vars.get("SQLQuery");
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(SQLQuery);
while(matcher.find())
{
String token = matcher.group(); //${var}
String tokenKey = matcher.group(1); // var
SQLQuery = SQLQuery.replaceFirst(Pattern.quote(token), Matcher.quoteReplacement(vars.get(tokenKey)));
}
vars.put("SQLQuery", SQLQuery);
You need to use a "Prepared Select Statement" as Query Type. Prepared Statements
Then replace your ${var} with ?
SELECT * FROM Table WHERE ID = ?
And add the 2 parameters at the bottom.
Parameter values: ${var}
Parameter types: INT

SQL: Use a predefined list in the where clause

Here is an example of what I am trying to do:
def famlist = selection.getUnique('Family_code')
... Where “””...
and testedWaferPass.family_code in $famlist
“””...
famlist is a list of objects
‘selection’ will change every run, so the list is always changing.
I want to return only columns from my SQL search where the row is found in the list that I have created.
I realize it is supposed to look like: in ('foo','bar')
But no matter what I do, my list will not get like that. So I have to turn my list into a string?
('\${famlist.join("', '")}')
Ive tried the above, idk. Wasn’t working for me. Just thought I would throw that in there. Would love some suggestions. Thanks.
I am willing to bet there is a Groovier way to implement this than shown below - but this works. Here's the important part of my sample script. nameList original contains the string names. Need to quote each entry in the list, then string the [ and ] from the toString result. I tried passing as prepared statement but for that you need to dynamically create the string for the ? for each element in the list. This quick-hack doesn't use a prepared statement.
def nameList = ['Reports', 'Customer', 'Associates']
def nameListString = nameList.collect{"'${it}'"}.toString().substring(1)
nameListString = nameListString.substring(0, nameListString.length()-1)
String stmt = "select * from action_group_i18n where name in ( $nameListString)"
db.eachRow( stmt ) { row ->
println "$row.action_group_id, $row.language, $row.name"
}
Hope this helps!

Use arguments value in sql statements

I am using jsp-jdbc and I want to use the value of a argument in sql statements.
For eg: http://localhost:3232/file.jsp?name="as"
In the jsp file containing jsp I want:
select * from books where name= (the value of argument 'name' in the url)
How will it do?
You can use HttpServletRequest#getParameter() to get the request parameter.
String name = request.getParameter("name");
// ...
You can use PreparedStatement#setXxx() to set an user-definied variable in a SQL string.
preparedStatement = connection.prepareStatement("SELECT * FROM books WHERE name=?");
preparedStatement.setString(1, name);
resultSet = preparedStatement.executeQuery();
// ...
Note that this job doesn't belong in a JSP, but in a Servlet (with a service/DAO class).
See also:
Advanced Servlets/JSP tutorial
JDBC tutorial - Prepared statements