MySQL view with a function to create an input variable - mysql

Is it possible to create an SQL view in MySQL that takes an input variable say as a function argument? I have found this caption from the MySQL web site but am not sure how to use it as I am quite new to SQL functions. When I run this in the MySQL command prompt ,it gives me errors. Also I am not sure if this is even what I am looking for?
create function book_subject
returns varchar(64) as
return #book_subject;
create view thematical_books as
select title, author
from books
where subject = book_subject();

You are getting errors because the CREATE FUNCTION syntax is incorrect (gotta love those MySQL manual user comments!). The correct syntax for creating this function is as follows:
CREATE FUNCTION book_subject()
RETURNS VARCHAR(64)
RETURN #subject;
The CREATE VIEW syntax is correct.
In order to use the view, you'll need to set the variable #book_subject before you select from the view:
SET #book_subject = 'Epic Poems';
Then when you do a:
SELECT *
FROM thematical_books;
It will return the title and author of all of the books that have a subject of 'Epic Poems'
This is a trick to get around the restriction of MySQL views that "The SELECT statement [of the view] cannot refer to system or user variables." You use a function that just returns the variable, and that function gets called each time the view is used.

This is about as close as you are likely to get. There isn't an official way to get any arguments passed into a view (because how do you supply the argument when the view is referenced in the FROM clause). Using a session global variable and a function as shown is about the only way to achieve the effect. It is sneaky and bug-prone - not good attributes for clean maintainable code.

Related

Rails6 how to do `XXX.update_all` with mysql function

I would like to use update_all in order to update all records in a database.
Let me assume that the name of the attribute to be update is price.
I succeeded command A.
A
MyModel.update_all(price: "$500")
However, I would like to mysql function(e.g. IF, CONCAT, arithmetic...) in updating.
so I tried command B, but failed and the string value CONCAT('$', 500) was stored.
B
MyModel.update_all(price: "CONCAT('$', 500)")
I succeeded when I tried C, but I don't want use it because of the SQL injection risks.
C
MyModel.update_all("price = CONCAT('$', 500)")
How can I do that without any risk of SQL injection attacks?
Here, I have to use sql function here for some reasons.
Thank you in advance.
You need to create methods corresponding to allowable sql functions that take the params as input. So if you want to provide "CONCAT(..,...)" then user should be able to call a method like this. You can extent it to check type of arguments are allowed and add checks there as well.
def allowed_functions(func_name, all_args_here)
case func_name
when 'concat' then "CONCAT(#{all_args_here})"
end
end

Why won't truncateTable work in Joomla 3.7?

I have the following code attempting to truncate a table. The Joomla documentation makes me believe this will work, but it does not. What am I missing?
$db = JFactory::getDbo();
truncate_query = $db->getQuery(true);
//$truncate_query = 'TRUNCATE ' . $db->quoteName('#__mytable');
$truncate_query->truncateTable($db->quoteName('#__mytable'));
$db->setQuery($truncate_query);
echo $truncate_query;
exit();
If I use the line that is commented out to manually generate the SQL, it does work. The reason I am still looking to use the truncateTable function is that I am trying to include the truncation in a transaction. When I use the manual statement, the table is still truncated even if another part of the transaction fails, which is annoying since the other statements rely on data that is truncated, so if the table is emptied when it shouldn't be there is no data left to run the transaction again. Very annoying!
Here's how you call/execute your truncation query:
JFactory::getDbo()->truncateTable('#__mytable');
And now some more details...
Here is the method's code block in the Joomla source code:
public function truncateTable($table)
{
$this->setQuery('TRUNCATE TABLE ' . $this->quoteName($table));
$this->execute();
}
As you can see the truncateTable() method expects a tablename as a string for its sole parameter; you are offering a backtick-wrapped string -- but the method already offers the backtick-wrapping service. (Even if you strip your backticks off, your approach will not be successful.)
The setQuery() and execute() calls are already inside the method, so you don't need to create a new query object nor execute anything manually.
There is no return in the method, so the default null is returned -- ergo, your $truncate_query becomes null. When you try to execute(null), you get nothing -- not even an error message.
If you want to know how many rows were removed, you will need to run a SELECT query before hand to count the rows.
If you want to be sure that there are no remaining rows of data, you'll need to call a SELECT and check for zero rows of data.
Here is my answer (with different wording) on your JSX question.

Why does MySQL permit non-exact matches in SELECT queries?

Here's the story. I'm testing doing some security testing (using zaproxy) of a Laravel (PHP framework) application running with a MySQL database as the primary store for data.
Zaproxy is reporting a possible SQL injection for a POST request URL with the following payload:
id[]=3-2&enabled[]=on
Basically, it's an AJAX request to turn on/turn off a particular feature in a list. Zaproxy is fuzzing the request: where the id value is 3-2, there should be an integer - the id of the item to update.
The problem is that this request is working. It should fail, but the code is actually updating the item where id = 3.
I'm doing things the way I'm supposed to: the model is retrieved using Eloquent's Model::find($id) method, passing in the id value from the request (which, after a bit of investigation, was determined to be the string "3-2"). AFAIK, the Eloquent library should be executing the query by binding the ID value to a parameter.
I tried executing the query using Laravel's DB class with the following code:
$result = DB::select("SELECT * FROM table WHERE id=?;", array("3-2"));
and got the row for id = 3.
Then I tried executing the following query against my MySQL database:
SELECT * FROM table WHERE id='3-2';
and it did retrieve the row where id = 3. I also tried it with another value: "3abc". It looks like any value prefixed with a number will retrieve a row.
So ultimately, this appears to be a problem with MySQL. As far as I'm concerned, if I ask for a row where id = '3-2' and there is no row with that exact ID value, then I want it to return an empty set of results.
I have two questions:
Is there a way to change this behaviour? It appears to be at the level of the database server, so is there anything in the database server configuration to prevent this kind of thing?
This looks like a serious security issue to me. Zaproxy is able to inject some arbitrary value and make changes to my database. Admittedly, this is a fairly minor issue for my application, and the (probably) only values that would work will be values prefixed with a number, but still...
SELECT * FROM table WHERE id= ? AND ? REGEXP "^[0-9]$";
This will be faster than what I suggested in the comments above.
Edit: Ah, I see you can't change the query. Then it is confirmed, you must sanitize the inputs in code. Another very poor and dirty option, if you are in an odd situation where you can't change query but can change database, is to change the id field to [VAR]CHAR.
I believe this is due to MySQL automatically converting your strings into numbers when comparing against a numeric data type.
https://dev.mysql.com/doc/refman/5.1/en/type-conversion.html
mysql> SELECT 1 > '6x';
-> 0
mysql> SELECT 7 > '6x';
-> 1
mysql> SELECT 0 > 'x6';
-> 0
mysql> SELECT 0 = 'x6';
-> 1
You want to really just put armor around MySQL to prevent such a string from being compared. Maybe switch to a different SQL server.
Without re-writing a bunch of code then in all honesty the correct answer is
This is a non-issue
Zaproxy even states that it's possibly a SQL injection attack, meaning that it does not know! It never said "umm yeah we deleted tables by passing x-y-and-z to your query"
// if this is legal and returns results
$result = DB::select("SELECT * FROM table WHERE id=?;", array("3"));
// then why is it an issue for this
$result = DB::select("SELECT * FROM table WHERE id=?;", array("3-2"));
// to be interpreted as
$result = DB::select("SELECT * FROM table WHERE id=?;", array("3"));
You are parameterizing your queries so Zaproxy is off it's rocker.
Here's what I wound up doing:
First, I suspect that my expectations were a little unreasonable. I was expecting that if I used parameterized queries, I wouldn't need to sanitize my inputs. This is clearly not the case. While parameterized queries eliminate some of the most pernicious SQL injection attacks, this example shows that there is still a need to examine your inputs and make sure you're getting the right stuff from the user.
So, with that said... I decided to write some code to make checking ID values easier. I added the following trait to my application:
trait IDValidationTrait
{
/**
* Check the ID value to see if it's valid
*
* This is an abstract function because it will be defined differently
* for different models. Some models have IDs which are strings,
* others have integer IDs
*/
abstract public static function isValidID($id);
/**
* Check the ID value & fail (throw an exception) if it is not valid
*/
public static function validIDOrFail($id)
{
...
}
/**
* Find a model only if the ID matches EXACTLY
*/
public static function findExactID($id)
{
...
}
/**
* Find a model only if the ID matches EXACTLY or throw an exception
*/
public static function findExactIDOrFail($id)
{
...
}
}
Thus, whenever I would normally use the find() method on my model class to retrieve a model, instead I use either findExactID() or findExactIDOrFail(), depending on how I want to handle the error.
Thank you to everyone who commented - you helped me to focus my thinking and to understand better what was going on.

Can I pass a MYSQL function as a value through an HTML Form?

I have an HTML form that I'm using to submit some SQL data. I'd like to pass the MYSQL function LAST_INSERT_ID() as a value but when I do this there are single tick marks that get added the the function upon insert and it fails, like this 'LAST_INSERT_ID()'.
I want to be able to use this function so I can call what that ID was.
Is it possible to pass this function successfully?
No, you can't pass SQL code instead of values and have it automatically executed on the server.
(Can you imagine how that could have been used by someone with not so good intentions...?)
You could send a special "magic" value, that the code on the server would recognise, and change the query to use last_insert_id() for the value. (You could use the function name as magic value, but you should probably use something less obvious.)
To insert code in a query like that, you need to create the SQL query dynamically. When you create queries dynamically, make sure to escape values properly so that the code isn't open to SQL injection attacks.

Condition check with IN clause mysql

I have a string returned from a function "'aa','bb','cc',..."(the function uses GROUP_CONCAT). I want to use this as a condition in the IN clase of mysql.
SELECT name,class,comment
FROM vwstudent v
WHERE name IN (select func())
I want the query to act like
SELECT name,class,comment
FROM vwstudent v
WHERE name IN ('aa','bb','cc','dd',..)
I assume ('aa','bb','cc','dd',..) is acting as a whole string here and isn't generating any result. What can I do to run this query error less.
I'm not sure if it'll help. But you might be able to hack something together by using PREPARE and EXECUTE as described here: How To have Dynamic SQL in MySQL Stored Procedure
... but that's completely new to me. I've never used anything like that in MySQL.