MYSQL MyTAP issue - mysql

My question may be stupid but I have a 2 days experience in MYSQL. I'm trying to use MyTAP for unit testing and face a problem .
here's the SQL code exucted on a mysql console:
drop procedure IF EXISTS tap.tstTableCount;
delimiter //
CREATE PROCEDURE tap.tstTableCount (IN db CHAR(64), IN tbl CHAR(64))
BEGIN
DECLARE l_sql VARCHAR (4000);
SET l_sql=CONCAT('SELECT COUNT(*)>0 FROM ',db,'.',tbl,';');
SET #sql=l_sql;
PREPARE s1 FROM #sql;
EXECUTE s1;
DEALLOCATE PREPARE s1;
END //
delimiter ;
call tap.tstTableCount('storibo','relationCategory'); /* This call works fine and returns 1 (true)*/
SELECT tap.ok(
tap.tstTableCount('storibo','relationCategory'),
'relationCategory contains data'
); /* this one returns :
ERROR 1305 (42000): FUNCTION tap.tstTableCount does not exist */
is it an issue with the MyTAP fmk or do I make a mistake in my syntax ?

The problem is your tap.tstTableCount is a PROCEDURE and not a FUNCTION. All the MyTAP tests are are FUNCTIONS, as noted by being able to call it in a SELECT statement. You cannot call a PROCEDURE from a SELECT statement, instead needing to call it via:
CALL tap.tstTableCount();
Unfortunately, your example is one that cannot simply be converted to a FUNCTION to be used by the mytap functions. Dynamic SQL is not permitted in FUNCTION, but is allowed in PROCEDURE.

Related

IF-ELSE Not Working While Calling a Procedure

I am trying to call a procedure with a MySQL command as an argument. Everything is working perfect, but last procedure call where there has been implemented a conditional statement is behaving badly. The error description encountered when the procedure is called is provided below:
Error Code: 1064. 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 'IF #CheckExists > 0 THEN
set #result= ('done')
For more information, here i am passing a statement that should have been implemented itself in a procedure (i guess, loops, cursors conditions has to be defined in a procedure in MySQL) and hence an error. But i could not figure this out as the database name (#dbname in this case) has to be passed dynamically and even i tried to make another procedure to make this work i end up with the same error.
Any help would be greatly appreciated.
Thanks
use test;
drop procedure if exists test;
set #dbname = 'test_qa';-- only for the sake of example. this is to be dynamically done
delimiter //
create procedure test(IN sqlCommand text)
begin
SET #tquery = sqlCommand;
PREPARE stmt FROM #tquery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
end//
delimiter ;
CALL test (concat('SET #CheckExists =(select COUNT(*) from ',#dbname,'.course
where Name = ''Computing'' and Value = ''True'')'));
-- call test ('select #CheckExists');
CALL test (concat('IF #CheckExists > 0 THEN
set #result = (''done'')
else
set #result = (''gone'')
end if'));
You can't use IF (or procedural code at all) in anonymous blocks in MySQL.
Use this:
CALL test('SET #result = CASE WHEN #checkExists > 0 THEN ''done'' ELSE ''gone'' END')

Mysql very strange behavior

I found two very strange problems in MySQL database.
My MySQL database version is 5.6.
Problem 1:
I have simple store procedure for update column value:
Store procedure is as below:
drop PROCEDURE if exists mysql_TestProc;
CREATE PROCEDURE mysql_TestProc(Finaltable VARCHAR(1024),ColTOProcess VARCHAR(1024)
,strFind TEXT,strReplace TEXT)
Label1:BEGIN
DECLARE code VARCHAR(1024) DEFAULT '00000' ;
-- Exception Handler
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1
code = RETURNED_SQLSTATE;
END;
-- generate dynamic Query
SET #s:=CONCAT('UPDATE ',FinalTable,' SET
',ColTOProcess,'=REPLACE(',ColTOProcess,',\'',strFind,'\',\'',strReplace ,'\');');
PREPARE stmt from #s;
EXECUTE stmt;
-- If any exeption during query execution then Exception Handler will
-- assign error code to "code" variable
-- else "code" variable will have default value.
IF code != '00000' THEN
-- Error found..
select code ;
LEAVE Label1;
END IF;
END;
call mysql_TestProc("AnyTableName","ColumnName","Find Value","Replace Value").
If you call above store procedure with appropriate parameters it will
successfully update value.
But in my database It successfully update value with error code "42S22".
I changed machine then everything works fine.
So This strange behavior is only with my machine and my database("_temp").
Problem 2:
I have simple procedure as below:
DROP PROCEDURE IF EXISTS mysql_PrepareLogTable;
CREATE PROCEDURE mysql_PrepareLogTable(LogTable VARCHAR(1024),code TEXT,comment TEXT,category VARCHAR(1024),timestamp DATETIME,duration VARCHAR(100),rows INT,msg TEXT)
BEGIN
SET code=CONCAT(comment,' \n ',code);
SET #tempprepare=CONCAT('INSERT INTO ',LogTable,' VALUES ("',code,'","',category,'","',timestamp,'","',duration,'",',rows,',','"',msg,'")');
PREPARE stmt from #tempprepare;
EXECUTE stmt;
END;
I can compile above store procedure script all my mysql databases except one database("test2").
Only in database "test2", I am not able to compile above store procedure script.
Even I drop the store procedure and then try to execute the script but still It failed to compile script in database "test2".
I am using Toad 6 and mysql workbench 6.0.
So, anyone has any idea about these two problems.
Thank You,
Ronak

In mysql dynamic stored proc, is #var required to build a prepared statement?

I have a similar stored proc (but longer). It is called from PHP (GET request on Apache)
delimiter //
CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64))
BEGIN
SET #full_statement = CONCAT('SELECT ',col,' FROM ',tbl );
PREPARE stmt FROM #full_statement;
EXECUTE stmt;
END
//
delimiter ;
From what I read, #s is a mysql session variable living as long as my session is alive.
The #s presence annoys me since I fear that 2 concurrent request on that stored
proc might play with this "global variable". So I tried to remove the '#' like this
delimiter //
CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64))
BEGIN
DECLARE full_statement VARCHAR(300);
SET full_statement = CONCAT('SELECT ',col,' FROM ',tbl );
PREPARE stmt FROM full_statement;
EXECUTE stmt;
END
//
delimiter ;
to build the prepared statement without success.
I seem to have constantly
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 'full_statement; EXECUTE stmt;
Does my fear of 2 calls within my php session is really a problem ?
(If not, what about having 200 stored procedures using that same
global variable) ?
Can I really achieve my goal and remove the '#' and let the prepared
statement being handle by a simple stored proc variable or is it a constraint of prepared statement ?
Regards.
Yes, the #var is required.
MySQL's PREPARE statement only accepts "user variables" (those prefixed with #), not local variables declared in a stored routine.
This has long been recognized as a WTF in MySQL:
Bug #17409 PREPARE doesn't support queries in local variables
Does my fear of 2 calls within my php session is really a problem ?
No. It's not a global variable, it's a session variable.
Two concurrent sessions have their own value for #var.

MySQL Stored Procedure Throwing Errors when called

When I create this stored procedure, I get no errors and it gets created just fine.
DELIMITER $$
CREATE DEFINER=`portaluser`#`%` PROCEDURE `sp_CreateDatabaseAndTablesByIdAndName`(
IN p_vendorId VARCHAR(256),
IN p_name VARCHAR(256)
)
BEGIN
SET #db_create = CONCAT('CREATE DATABASE IF NOT EXISTS xx_client_', p_vendorId, '_', p_name);
PREPARE stmt FROM #db_create;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
When I call this stored procedure, it creates the database, yet throws a warning: 1295 This command is not supported in the prepared statement protocol yet.
CALL sp_CreateDatabaseAndTablesByVidAndName('11111', 'xx');
I can't seem to find anywhere online that tells me exactly why this is throwing an error, seeing as though it's a fairly simple query. I've seen other people do essentially the same thing without any problems. I need a second set of eyes to tell me where I'm going wrong. Any help is appreciated.
**Note: I had previously changed p_VendorId to an INT(11) and called it the following way, but still got the same error:
CALL sp_CreateDatabaseAndTablesByVidAndName(11111, 'xx');
Turns out it was because I did this:
END
Rather than:
END $$
DELIMITER ;

can procedures within mysql triggers work?

Can a stored procedure plus a sql query be executed from within a trigger?
procedure plus query
SET #tmp = (SELECT fvalue FROM ftable WHERE id=2);
SET #SQL = CONCAT('INSERT INTO ',#tmp,' VALUES (''buhambug'')');
PREPARE stmt FROM #SQL;
EXECUTE stmt;
If so what are the rules and links to examples? I have't been able to find any.
Yeah, you can call a stored procedure from a trigger like this:
Create trigger foo after insert on table for each row
BEGIN
call your_procedure(params);
END$$
Note the ending delimiter. If ; is the default delimiter inside the trigger as well, then it won't work, for MySQL will treat each command separately and throw error. You want the entire code inside the trigger to be executed together. hence declare a different delimiter, like $$ prior to defining the trigger, through Delimiter $$. Then, ; will work correctly inside the the trigger. After you terminate the trigger through $$, don't forget to restore the default delimiter.