Mysql function return system result - mysql

In mysql, I'm trying to create a function that will return the result of a bash command. I've created a simplified version of what I'm trying to do to make it easier to understand.
I have a file called mycmd.sh, and inside it, I have this line:
echo $1 'test'
When in mysql, I execute the sh file it is working fine
system ~/mycmd.sh 'test'
But I would like to be able to call it while doing a select in mysql, something like this
select myFunc(username) from user;
The result will be that, every username will have a "test" after it.
The problem is when I try to create the mysql function
CREATE FUNCTION myFunc(s VARCHAR(500)) RETURNS VARCHAR(505)
RETURN SYSTEM ~/mycmd.sh s;
I always get the error: ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '~/mycmd.sh s' at line 2
I tried putting it in quote, or in a variable, or in a prepared statement, but nothing seem to work...
Anyone have an idea how to do so?
Thank you

Unfortunately what you are trying to do isn't possible without using a UDF (User Defined Plugin). The system command you're using is part of the MySQL shell, not an actual MySQL function, which is why it doesn't work in the function you're trying to define.
The only other option I can think of is to write a procedure that imitated whatever your external command was going to do.

Related

Getting a formatting error on the output of any MySQL stored procedure I try

I am sure that I am missing some small but important detail, but need to help to see why I am consistantly getting an error when I add in the SELECT #output in my input like this. I have looked at many aritcles and answers but none of them are quite what I am looking at:
let connection = mysql.createConnection(config,{CLIENT_MULTI_RESULTS: true});
(this line is the issue)
**let sql = 'CALL sp_whatever(?,#usernameOut);select #usernameOut;'**
await connection.query(sql, [param1],
function(err,rows){
console.log("INSIDE MySQL1");
I am doing this in Node JS and most examples are acutally in PHP. I have not found anything that is exactly what I am looking for (why am I getting a formatting error when I set it up like other examples or tutorials?)
I am using MySQL 5.7 on my Azure LInux server and the MySQL stored procedure looks like this: (in case the issue is inside the Stored Procedure itself)
CREATE DEFINER=`someDB`#`%` PROCEDURE `GetUsername`(
IN userIdVal INT,
OUT usernameOut NVARCHAR(45)
)
BEGIN
SELECT username INTO usernameOut
FROM players
WHERE userId = userIdVal AND avatarId = 0 AND Gender IS NULL AND active = 1 ;
END
This is the error I am getting:
err.message: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select #username' at line 1
It turns out that my real problem was a Node JS one. I was unable to get the output because it was a second command. I had read that I needed to add in multipleStatements: true if I wanted/needed to process multiple commands. What I didn't figure out until tonigt was that it had to be added to the config file to work correctly. Works great now!

mysql-connector-python adds single quotes around table name when table is passed as argument. Table name comes from Flask session variable

I am new to MySQL and I am building a Flask project and using mysql.connector to query a MySQL Database. I know this question has been answered many times before but this is more specific to using MySQL with Flask.
I need to pass a query where I want to plug in the table name into the query, dynamically, depending on the value stored in the session variable in Flask. But the problem is, if I try to do:
Method 1:
cur.execute('SELECT * FROM %s;',(session['table_name'],))
the database throws an error stating that such a table is not found. However, the problem is mysql.connector keeps enclosing the table name with single quotes, hence the error.
Sample Error Statement:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''52_data'' at line 1
Here the table name should be 52_data and not '52_data'.
Only other workaround, I figured, is using:
Method 2:
cur.execute('SELECT * FROM '+session['table_name']+';')
which is working but it does not escape SQL Injection, I am guessing, since it's direct concatenation, unlike Method 1, where the cur.execute() function handles the escaping, as per this question.
The value being passed is stored in a sessions variable in Flask, which is not so secure, as per Miguel's Video. Hence, I want to escape that string, without triggering off an error.
Is it possible to implement Method 1 in a way that it does not add the quotes, or maybe escape the string using some function? Or maybe any other Python/Flask package that can handle this problem better?
Or if nothing works, is checking for SQL Injection manually using regex is a wiser option?
Thanks in advance.
Note: The package name for this mysql.connector is mysql-connector-python and not any other same sounding package.
For identifiers, you can use something like:
table_name = conn.converter.escape(session['table_name'])
cur.execute('SELECT * FROM `{}`'.format(table_name))
For values placeholders, you can use your Method 1, by using the parameters in the cur.execute() method. They will be escaped and quoted.
More details in https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
NOTE: You don't need to end the SQL statements with ;

You have an error in your SQL syntax near '<!

Trying to relocate a Wordpress DB and are running in to this issue all the time.
Been trying all the normal stuff to get it working optimizing, repairing etc and also try to import it with several tools (Sequel pro etc ) and over ssh.
Have the issue occurring over several tables and can see that other's have had the same. Because i can't import any copy i would need some expertise advice how to solve this either in phpmyadmin or ssh.
Error message is
#mysql -u -p db < /tmp/file.sql
> ERROR 1064 (42000) at line 109088: You have an error in your SQL
> syntax; check the manual that corresponds to your MySQL server version
> for the right syntax to use near '<!
> <div class="error"><h1>Error</h1> <p><strong>SQL query:</strong> <a href=' at line 1
Don't really know how to approach it because i find this all over the DB
like
<image:caption><![CDATA
Any advice?
Since "all the normal stuff" isn't working...
I'm going to take a guess, you are a running something to "copy" the contents of a database table, or you're doing some sort of "dump" or "export" that creates SQL statements.
And the SQL statements that are running against the target are throwing an error.
We can't tell (from where we're sitting and what we're seeing) what it is you are actually doing, we're just guessing.
The two most likely possibilities:
Whatever tool you are using isn't expecting that the column values being copied might contain values that need to be "escaped" if that value is incorporated in the text of a SQL statement. For example, suppose I have a column value like this:
I'd like a pony
and If I grab that value and I naively stick that into the text of a SQL statement, without regard for any characters it might contain, e.g.
INSERT INTO foo (bar) VALUES ('I'd like a pony');
If I try to execute that statement, MySQL is going to throw a syntax error. MySQL is going to see a string literal with a value of 'I' (the single quote that is part of the string is now being seen as the end of the string literal. MySQL is going to flag a syntax error on what follows d like a pony.
When we take a value and build a SQL statement from it, we have to properly escape the values. In this example, the insert statement to reproduce that string value could look like this:
INSERT INTO foo (bar) VALUES ('I''d like a pony');
^^
If this is what's happening, you can be thankful that the column values didn't include something more nefarious...
Robert'); DROP TABLE students; --
But without seeing the actual SQL statement that is being executed, this is just a guess at what is causing the issue.
Is there some kind of guide or some instructions that you are following to "relocate a Wordpress DB" which documents "all the normal stuff" that you are doing?
FOLLOWUP
Question was edited to add this information:
mysql -u -p db < /tmp/file.sql
What's important here is the contents of file.sql.
The problem is most likely in the part of "all the normal stuff" is producing that file. That part is effectively broken because it's not expecting that an extracted column value can contain a single quote character, and is not properly escaping the value before it's incorporated into the text of a SQL INSERT statement.

The MySQL "DELIMITER" keyword isn't working

Ok so, I've been ripping my hairs ou on this one, why doesn't this work?
DELIMITER |
CREATE PROCEDURE Decrypt_pw()
READS SQL DATA
BEGIN
SELECT 'Hey Select';
END|
It's so basic and I'm pretty sure I'm using the correct syntax, what am I missing?
Error:
21:14:07 [DELIMITER - 0 row(s), 0.000 secs] [Error Code: 1064, SQL State: 42000] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER |
CREATE PROCEDURE Decrypt_pw()
READS SQL DATA
BEGIN
SELECT 'He' at line 1
21:14:07 [END| - 0 row(s), 0.000 secs] [Error Code: 1064, SQL State: 42000] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END|' at line 1
I'm using DbVisualizer, latest version, could this problem be with the software itself?
Perhaps I should explain myself better, the passwords are encrypted in my database (no need to worry), and this allows me to decrypt them, this is for a personal project I'm working on.
I was trying to develop a script that would allow me to run it and set up the necessary databases, tables, etc for that to work, and I require some SPs which must also be created, I'm trying to create an SP through a mysqli_query, is that even possible?
Basically it's for a "setup script" of a php application.
UPDATE: Seems that this is supposed to work, however I can't use objects due to the guys at HostGator -.- not allowing for objects in PHP.
I Have pretty much given up on mysqli since it's just not going to work I'm trying with shell_exec, I'm creating the procedure but when I check the ddl it's empty, it's creating empty procedures but at least it's doing something...
it is probaly a software version problem... i tried your code and it works just fine for me...
try this
DELIMITER //
CREATE PROCEDURE Decrypt_pw()
READS SQL DATA
BEGIN
SELECT 'Hey Select';
END //
DELIMITER ;
At least as of 9.1, DBVisualizer doesn't support the DELIMITER keyword. Here's the way they do it: link.
Definitely Not an elegant work-around ... but it works.
All the usual caveats about not shelling out, yada yada yada.
// here's the core stored procedure code
$stored = <<<EOT
CREATE PROCEDURE Decrypt_pw()
READS SQL DATA
BEGIN
SELECT * FROM whatever;
END #
EOT;
// first, shell out to change the delimiter using mysql command-line
shell_exec('mysql -u user -ppassword -e "DELIMITER #");
// assuming $pdo is a valid PDO connection
// send the command to create the stored procedure:
$pdo->exec($stored);
// now shell out again to change the delimiter back
shell_exec('mysql -u user -ppassword -e "DELIMITER ;");
Try putting space between 'DELIMITER' and '|'.
It worked for me.
DELIMITER | --here
CREATE TRIGGER my_trigger BEFORE INSERT
ON employee
FOR EACH ROW BEGIN
INSERT INTO trigger_test VALUES('added new employee');
END |
DELIMITER;

Cannot use a MySQL UDF function

I have loaded an UDF function into MySQL (without having selected any particular DB). It used to work well during my session but now I get the error "ERROR 1305 (42000): FUNCTION currentdatabase.myfunction does not exist" when I try to use the function with the following sql statement :
select myfunction('aaa');
I then tried to drop the function and I got the same error code :
mysql> drop function myfunction;
ERROR 1305 (42000): FUNCTION database.myfunction does not exist
if a DB is selected.
Another error code otherwise :
ERROR 1046 (3D000): No database selected
So I decided to specify again the function and I got the following error code :
CREATE FUNCTION myfunction RETURNS INT SONAME 'myfunction.so';
ERROR 1125 (HY000): Function 'myfunction' already exists
My question is: how to use again my function ?
Thanks in advance.
Note: there is no space problem like ("select myfunction ('aaa');") as reported on several other websites.
I recently encountered this issue my self and I put together a quick blog post about it:
When installing a UDF recently I got an
annoying error message, which didn't seem to want to go away. Deleting
the function before attempting to remove it did not work so I used the
following set of escalating commands to attempt to get it to
install. But back to the error for a moment:
bash > mysql -u user -p < installdb.sql
Enter password:
ERROR 1125 (HY000) at line 7: Function 'lib_mysqludf_ssdeep_info' already exists This can be
solved really simply with the following options:
Attempt
to delete the function and then reinstall it Delete the
function row from the mysql.func table and then reinstall it
Stop the MySQL server (after trying option 2), start it again and
then reinstall it
From my testing you do not need to have backups of your binary database files as #jmcejuela suggests in his answer.
Source: http://simonholywell.com/post/2012/01/mysql-udf-install-error-function-already-exists.html
I believe the problem comes from removing the .so library before dropping the function/s. The server still believes it has the functions since they appear in SELECT * FROM mysql.func but of course calling these functions fail. Somehow DROP doesn't simply remove entries in this table but also checks whether the libraries are found which makes this fail. CREATE supposedly just check first the func table which makes this fail...
The solution is to restore the func table (func.MYI, func.MYD, func.frm files under your mysql's data/mysql) to the point everything matches.
Luckily I had a backup of these files. Otherwise you will have to backup them from a new mysql installation (you could simply install locally a new server not to remove your current one)
Bottom line: do not remove the .so libraries before dropping the functions.
Got some of these errors when swapping out (not dropping) the .so library before dropping the function(s).
Restarting the server eliminated the error messages, whether the functions were successfully dropped or not. Mysqld just looked at the mysql.func table and loaded functions from the (new) .so. I know restarting the server is not always an option, but if it is, it's fast and complete.