MySQL trigger on insert of text going into infinite loop - mysql

There are three tables: users, ap_name_bank_m and ap_name_bank_h. users table has three columns 'name_eng' (name of user in english), 'name_gdn_eng'(name of user's guardian in english) and 'category'.
ap_name_bank_m and ap_name_bank_h are corpus of names for each category of name: 'm' or 'h'.
When a row is updated I want to check if each word of both names in present in either of two tables ap_name_bank_m and ap_name_bank_h.
Whichever count is higher that category will be assigned. The below code which I have written is going into infnite loop and I am getting "MySQL server has gone away error". Can someone tell me where I am wrong?
Assume name_eng and name_gdn_eng will only contain words with spaces and nothing else.
DELIMITER $$
create trigger set_cat before update on users_table for each row
BEGIN
declare words text;
declare word varchar(50);
declare num_m int default 0;
declare num_h int default 0;
declare len int default 0;
set words = concat(new.name_eng,' ',new.name_gdn_eng);
iterator:
LOOP
set word = substring_index(words,' ',1);
set num_m = EXISTS(select 1 from ap_name_bank_m where name=word) + num_m;
set num_h = EXISTS(select 1 from ap_name_bank_h where name=word) + num_h;
set words = trim(replace(words,word,''));
END LOOP iterator;
if (num_m > num_h) then set new.category='M'; end if;
if (num_h > num_m) then set new.category='H'; end if;
END $$
DELIMITER ;

I found a better way to do this. No need for loop.
BEGIN
declare words text;
declare word varchar(50);
declare num_m int default 0;
declare num_h int default 0;
set words = concat(new.name_eng,' ',new.name_gdn_eng);
set num_h = (select count(*) from ap_name_bank_h where match(name) against (words in natural language mode));
set num_m = (select count(*) from ap_name_bank_m where match(name) against(words in natural language mode));
/*
iterator:
LOOP
set word = substring_index(words,' ',1);
set num_m = EXISTS(select 1 from ap_name_bank_m where name=word) + num_m;
set num_h = EXISTS(select 1 from ap_name_bank_h where name=word) + num_h;
set words = trim(replace(words,word,''));
END LOOP iterator;*/
if (num_m > num_h) then set new.category='M'; end if;
if (num_h > num_m) then set new.category='H'; end if;
END

Related

how does mysql user defined function know a selected row was found?

a MYSQL user defined function selects a row from a table. How does the UDF code determine if the selected row was found in the table?
CREATE FUNCTION snippetFolder_folderPath(folder_id int)
RETURNS varchar(512)
BEGIN
declare vFolder_id int;
declare vParent_id int;
declare vPath varchar(512) default '';
declare vFolderName varchar(256) default '';
set vFolder_id = folder_id;
build_path:
while (vFolder_id > 0) do
/* -------- how to know this select statement returns a row?? ---------- */
select a.parent_id, a.folderName
into vParent_id, vFolderName
from SnippetFolder a
where a.folder_id = vFolder_id;
if vPath = ' ' then
set vPath = vFolderName;
else
set vPath = concat_ws( '/', vFolderName, vPath );
end if ;
set vFolder_id = vParent_id;
end while ;
return vPath;
END
https://dev.mysql.com/doc/refman/8.0/en/select-into.html says:
If the query returns no rows, a warning with error code 1329 occurs (No data), and the variable values remain unchanged.
So you could declare a continue handler on warnings, something like the example from the documentation:
BEGIN
DECLARE i INT DEFAULT 3;
DECLARE done INT DEFAULT FALSE;
retry:
REPEAT
BEGIN
DECLARE CONTINUE HANDLER FOR SQLWARNING
BEGIN
SET done = TRUE;
END;
IF done OR i < 0 THEN
LEAVE retry;
END IF;
SET i = i - 1;
END;
UNTIL FALSE END REPEAT;
END
I'll leave it to you to read the documentation and adapt that example to your table and your loop.
Alternatively, if you're using MySQL 8.0 you can use recursive common table expression:
CREATE FUNCTION snippetFolder_folderPath(vFolder_id int)
RETURNS varchar(512)
BEGIN
DECLARE vPath varchar(512) DEFAULT '';
WITH RECURSIVE cte AS (
SELECT folderName, parent_id, 0 AS height
FROM SnippetFolder WHERE folder_id = vFolder_id
UNION
SELECT f.folderName, f.parent_id, cte.height+1
FROM SnippetFolder AS f JOIN cte ON cte.parent_id = f.folder_id
)
SELECT GROUP_CONCAT(folderName ORDER BY height DESC SEPARATOR '/')
INTO vPath
FROM cte;
RETURN vPath;
END
The recursive CTE result is all the ancestors of the row matching vFolder_id, and then one can use GROUP_CONCAT() to concatenate them together as one string.

MySQL IN Clause in SQL query with User Defined Function

I am using following query to update all the children of particular topic.
UPDATE topics SET reuse = 0 WHERE topic_id IN (SELECT GetChildTopics(187));
Where
SELECT GetChildTopics(187);
returns "188,190,189" but my update query is updating only first row with topic_id = 188, instead of updating first topic only, it should update all 3 topics.
When I put the values manually it works fine.
UPDATE topics SET reuse = 0 WHERE topic_id IN (188,190,189);
Can anyone suggest what's wrong I am doing here?
Here is the code for GetChildTopics MySQL Function
CREATE DEFINER=`root`#`localhost` FUNCTION `GetAncestry`(GivenID INT) RETURNS varchar(1024) CHARSET latin1
DETERMINISTIC
BEGIN
DECLARE rv VARCHAR(1024);
DECLARE cm CHAR(1);
DECLARE ch INT;
SET rv = '';
SET cm = '';
SET ch = GivenID;
WHILE ch > 0 DO
SELECT IFNULL(parent_topic_id,-1) INTO ch FROM
(SELECT parent_topic_id FROM topic_list WHERE id = ch) A;
IF ch > 0 THEN
SET rv = CONCAT(rv,cm,ch);
SET cm = ',';
END IF;
END WHILE;
RETURN rv;
END
Try this;)
UPDATE topics SET reuse = 0 WHERE FIND_IN_SET(topic_id, GetChildTopics(187));

MySQL Cursor Fetch not working

I have the following stored procedure that is meant to implement Dijkstra's shortest path algorithm:
CREATE PROCEDURE `Dijkstras`(IN `pids` VARCHAR(512), IN `startP` VARCHAR(8), IN `endP` VARCHAR(8), OUT `dist` DECIMAL(20,10), OUT `eset` VARCHAR(1024))
BEGIN
DECLARE currentP VARCHAR(4);
DECLARE finished INT DEFAULT 0;
DECLARE pt_from, pt_to int;
DECLARE pt_dist decimal(20,10);
DECLARE done INT DEFAULT 0;
DECLARE cur2 CURSOR FOR
select F.id as `from`, T.id as `to`, dist(F.lat, F.lng, T.lat, T.lng)
as dist
from sampledata F, sampledata T
where F.id < T.id and
find_in_set(convert(F.id, char(10)), pids) and
find_in_set(convert(T.id, char(10)), pids)
order by dist;
DECLARE CONTINUE HANDLER FOR not found SET done = 1;
SET currentP= startP;
SET eset = '';
SET dist = 0;
SET done=0;
OPEN cur2; -- this finds pariwise distances in miles.
REPEAT
FETCH cur2 INTO pt_from, pt_to, pt_dist;
SET dist= dist+pt_dist;
SET eset= CONCAT(eset, ',');
IF(currentP=pt_from OR currentP=pt_to) AND
(IN_SET(pt_from,pids) AND IN_SET(pt_to,pids)) THEN
BEGIN
SET dist= dist+ pt_dist;
SET pids= REMOVE_MEMBER(currentP, pids);
SET eset = concat(eset, ',', concat(pt_from, ':', pt_to));
IF left(eset, 1) = ',' then
SET eset = substring(eset, 2); -- remove extra comma.
END IF;
IF currentP=pt_from THEN
SET currentP=pt_to;
ELSE
SET currentP=pt_from;
END IF;
IF currentP= endP THEN
SET finished= 1;
END IF;
END;
END IF;
UNTIL done
END REPEAT;
CLOSE cur2;
END
My issue is that the cursor isn't working properly. When I fetch the current row into pt_from, pt_to, and pt_dist all I get are NULL values. The sampledata table is properly stored in the database and all the point ids in pids are also in the sampledata table. Plus this EXACT code works for another procedure, but reusing it here isn't working.
Anybody know what I'm doing wrong?
The error was that I passed in the point ids like this '12, 15, 18' with spaces in between. MySQL counts the whitespace when it parses the strings, and the id's in the table were listed without spaces. The correct way to pass in the string set is '12,15,18'.

mysql trigger function

I have a table call lp_upload and it contain plate number of car and other related information:
CREATE TABLE `lp_upload` (
`date` date NULL ,
`plate` char(10) NULL ,
`site` int NULL ,
`dateid` char(20) NULL
)
;
this table is getting information from a traffic camera. however, sometime letter in the plate is not recognized and it will be replace by $. So if a plate is really abc123, but the camera didnt recognized c and 1, it will be ac$$23 that get enter into the table.
im suppose to make it so when a new plate is entered and 6 of its letters match an existing plate, it will become that plate. EX: 123$5678 is entered and 12345678 already exist, then 123$5678 will be replace by 12345678.
so i first wrote a match function:
CREATE DEFINER = CURRENT_USER FUNCTION `matchingfun`(`str1` char(10),`str2` char(10))
RETURNS int
BEGIN
DECLARE myindex int DEFAULT 0;
DECLARE count int DEFAULT 0;
DECLARE maxlength int;
SET maxlength = length(str1);
for_loop: LOOP
SET myindex = myindex + 1;
IF maxlength < myindex then
RETURN 0;
END IF;
IF SUBSTRING(str1,myindex,1)= SUBSTRING(str2,myindex,1)then
SET count = count +1;
END IF;
IF count > 6 then
RETURN 1;
END IF;
IF SUBSTRING(str1,myindex,1)!= SUBSTRING(str2,myindex,1) and SUBSTRING(str1,myindex,1)!= '$' and SUBSTRING(str2,myindex,1)!= '$'then
RETRUN 0;
END IF;
END LOOP for_loop;
RETURN 0;
END
and I added a trigger function to the table
CREATE TRIGGER `trigger1` AFTER INSERT ON `lpr_opt_upload`
BEGIN
declare old_site_id int;
declare old_text char(10);
select lpr_text into old_text from lpr_opt_upload where matchingfun(new.lpr_text, lpr_text) = 1;
if(old_text is not null) then
set new.lpr_text = old_text;
end if;
END
when i run this, the database crashes. can you help fix this problem or suggest a better way to do this. thanks.
I suspect that the problem you're running into is multiple matches. For example, if you have abcd01234 and abcde1234 in the database and attempt to insert abcd$1234, you'll get an error.
Now, I'm going to assume that this application is supposed to match OCR'd license plates from speed cameras or red-light cameras in order to facilitate ticketing of the vehicle owner. If that's the case, then you want to err on the side of caution and not have the system automatically try to pick from multiple candidates and instead have a real human look at the result and confirm the plate number.
So, operating on that assumption:
DELIMITER //
CREATE TRIGGER `attempt_match_existing_plate`
BEFORE INSERT
ON `lp_upload`
FOR EACH ROW BEGIN
DECLARE exist_plate CHAR(10);
DECLARE rowcount INT;
SELECT COUNT(*), plate INTO rowcount, exist_plate FROM lp_upload WHERE platematch(NEW.plate, plate) = 1;
IF (1 = rowcount) AND (exist_plate IS NOT NULL) THEN
SET NEW.plate = exist_plate;
END IF;
END
//
DELIMITER ;
DELIMITER //
CREATE DEFINER = CURRENT_USER
FUNCTION `platematch`(`plate_new` char(10), `plate_exist` char(10))
RETURNS INT
BEGIN
DECLARE myindex INT DEFAULT 0;
DECLARE match_count INT DEFAULT 0;
DECLARE maxlength INT;
SET maxlength = length(plate_new);
for_loop: LOOP
SET myindex = myindex + 1;
IF maxlength < myindex THEN
RETURN 0;
END IF;
IF SUBSTRING(plate_new, myindex, 1) = SUBSTRING(plate_exist, myindex, 1)
THEN
SET match_count = match_count +1;
END IF;
IF match_count >= 6 THEN
RETURN 1;
END IF;
IF SUBSTRING(plate_new, myindex, 1) != SUBSTRING(plate_exist, myindex, 1)
AND SUBSTRING(plate_new, myindex, 1) != '$'
AND SUBSTRING(plate_exist, myindex, 1) != '$'
THEN
RETURN 0;
END IF;
END LOOP for_loop;
RETURN 0;
END
//
DELIMITER ;
In the scenario I described above, abcd$1234 will be inserted into the database as-is instead of just being matched to one of multiple potential results automatically.

Trigger syntax and IF ELSE THEN

I'd like to create a trigger which count the number of rows with a specific id (id_ort).
If it found more than 5 rows, I need to increment a variable.
Trigger Syntax
BEGIN
DECLARE nb INT;
DECLARE nba INT;
SET nba =0;
SET NEW.`VPLS_ID_NodeB` = CONCAT("21100", LPAD(NEW.`VPLS_ID_NodeB`,4,0));
SET nb = (SELECT COUNT(DISTINCT(`VPLS_ID_aggregation`)) FROM `VPLS_nodeB` WHERE `id_ORT` = NEW.`id_ORT`);
IF(nb > 5) THEN
SET nba = nb + 1;
ELSE
SET nba = nb;
END IF;
SET NEW.`VPLS_ID_aggregation` = CONCAT("21188", LPAD(NEW.`id_ORT`,2,0), LPAD(nba,2,0));
END
However, there is a bug... Even if i've less than 5 rows, the var is incremented each time.
Any ideas? Maybe it's a syntax problem...
Thanks a lot!
you probably forgot to specify a delimiter i've also made a few other changes as you can see
delimiter #
create trigger VPLS_nodeB_before_ins_trig before insert on VPLS_nodeB
for each row
BEGIN
DECLARE nb INT default 0;
DECLARE nba INT default 0;
SET NEW.VPLS_ID_NodeB = CONCAT('21100', LPAD(NEW.VPLS_ID_NodeB,4,0));
SET nb = (SELECT COUNT(DISTINCT(VPLS_ID_aggregation)) FROM VPLS_nodeB WHERE id_ORT = NEW.id_ORT);
IF(nb > 5) THEN
SET nba = nb + 1;
ELSE
SET nba = nb;
END IF;
SET NEW.VPLS_ID_aggregation = CONCAT('21188', LPAD(NEW.id_ORT,2,0), LPAD(nba,2,0));
END#
delimiter ;