MySQL trigger regexp not working - mysql

I am trying to group users by their email address.
REGEXP is not working. Help
BEGIN
DECLARE group_id tinyint(4);
SET #user_email = ( SELECT email FROM `users` WHERE id = NEW.id );
IF (SELECT #user_email REGEXP '\.com$') THEN SET group_id = 17;
ELSE SET group_id = 18;
END IF;
INSERT INTO `user_usergroup_map` (`user_id`, `group_id`) VALUES (NEW.id, group_id);
END
--------- New -------------------
I did some more testing.
This worked...
BEGIN
INSERT INTO `user_usergroup_map` (`user_id`, `group_id`) VALUES( 3, 18 );
END
But this didn't work
BEGIN
INSERT INTO `user_usergroup_map` (`user_id`, `group_id`) VALUES(
NEW.id, 18);
END

Rather than try to figure out what is not working, let me suggest this simplification:
BEGIN
INSERT INTO `user_usergroup_map` (`user_id`, `group_id`)
SELECT NEW.id,
IF( email REGEXP '[.]com$', 17, 18 )
FROM users
WHERE id = NEW.id;
END
One difference: Your version will always insert a row; mine won't if id is missing from users.

Related

Mysql procedure loop through to assign comma separated id doesn't work

I have a Mysql table as follows:
CREATE TABLE `login_info` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` varchar(50) NOT NULL,
`device_id` varchar(50) NOT NULL, /*Values can be WEB, IOS, ANDRIOD, OTHER */
`timestamp` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `login_info_uniq01` (`user_id`, `device_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
There are 12 rows in the table as follows:
INSERT INTO `login_info` (`id`, `user_id`, `device_id`, `timestamp`)
VALUES
(1, 'extend.10300000001', 'WEB', 1667235600001),
(2, 'extend.10300000002', 'IOS', 1667235600002),
(3, 'extend.10300000003', 'ANDRIOD', 1667235600003),
(4, 'extend.10300000004', 'OTHER', 1667235600004),
(5, 'extend.10300000005', 'WEB', 1667235600005),
(6, 'extend.10300000006', 'ANDRIOD', 1667235600006),
(7, 'extend.10300000007', 'WEB', 1667235600007),
(8, 'extend.10300000008', 'OTHER', 1667235600008),
(9, 'extend.10300000009', 'ANDRIOD', 1667235600009),
(10, 'extend.10300000010', 'IOS', 1667235600010),
(11, 'extend.10300000011', 'WEB', 1667235600011),
(12, 'extend.10300000012', 'OTHER', 1667235600012);
I would like to update the timestamp in chunk of 2 at a time where device_id = 'WEB' using IN clause on id column, for which I assign comma separated id through the loop, but when the update query trigger it updates only one row at a time instead of multiple ids.
The extend_login_timestamp_using_params procedure is as follows:
DELIMITER ;;
DROP PROCEDURE IF EXISTS `extend_login_timestamp_using_params` ;;
CREATE PROCEDURE `extend_login_timestamp_using_params`()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE login_info_id BIGINT;
DECLARE cur CURSOR FOR SELECT `id` FROM `login_info` WHERE `device_id` = 'WEB';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
SET #extended_timestamp = (SELECT UNIX_TIMESTAMP(DATE_FORMAT('2022-11-10' + INTERVAL 365 DAY,'%Y-%m-01 23:59:59')) * 1000);
SET #id_list = NULL;
SET #id_count = 0;
PREPARE extend_expire_statement FROM 'UPDATE login_info SET timestamp = ? WHERE id in (?)';
OPEN cur;
REPEAT FETCH cur INTO login_info_id;
SET #id_list = CONCAT_WS (',', #id_list, login_info_id);
SET #id_count = #id_count + 1;
IF (#id_count = 2) THEN
SELECT CONCAT('Inside loop #id_list: ', #id_list) as log; /* log: Inside loop #id_list: 1,5 */
EXECUTE extend_expire_statement USING #extended_timestamp, #id_list; /*update only where id = 1, ignore id = 5*/
SET #id_list = NULL;
SET #id_count = 0;
END IF;
UNTIL done END REPEAT;
DEALLOCATE PREPARE extend_expire_statement;
CLOSE cur;
IF (#id_list IS NOT NULL) THEN
EXECUTE extend_expire_statement USING #extended_timestamp, #id_list;
DEALLOCATE PREPARE extend_expire_statement;
END IF;
END;;
DELIMITER ;
After running the procedure when run the following query:
SELECT * FROM login_info WHERE device_id = 'WEB';
Expected Result:
id
user_id
device_id
timestamp
1
extend.10300000001
WEB
1698857999000
5
extend.10300000005
WEB
1698857999000
7
extend.10300000007
WEB
1698857999000
11
extend.103000000011
WEB
1698857999000
Actual Result:
id
user_id
device_id
timestamp
1
extend.10300000001
WEB
1698857999000
5
extend.10300000005
WEB
1667235600005
7
extend.10300000007
WEB
1698857999000
11
extend.103000000011
WEB
1667235600011
I don't understand when I log the id_list(1,5) it logs all the ids but why can update only the 1st id of the loop?
I am not sure what I need to change to extend_login_timestamp_using_params so that it can work as expected.
Any help will be much appreciated. Thanks in advance!

How to write conditional query in MySQL?

I came from MSSQL and I'm trying to learn MySQL.
Documentation seem to not help me.
I don't want my query to start always with SELECT, I want my query to SELECT, INSERT or UPDATE depending on the condition. I can't seem to do it with MySQL. Here is my code:
IF COALESCE((SELECT 1 FROM gt_postmeta WHERE meta_value = '12345' LIMIT 1), 0) THEN
BEGIN
INSERT INTO gt_posts (
post_date,
post_content,
post_title,
post_name,
post_type )
VALUES (
'',
'0000493729150.jpg',
'SHAMROCK',
'',
'');
SET #parent_id = (SELECT id FROM gt_posts ORDER BY id DESC LIMIT 1);
INSERT INTO gt_postmeta(
post_id,
meta_key,
meta_value)
VALUES
(#parent_id, '_visibility', 'visible'),
(#parent_id, '_price', 'H72 SEMI-GLOSS DARK EARTH'),
(#parent_id, '_regular_price', 'H72 SEMI-GLOSS DARK EARTH'),
(#parent_id, '_sku', '12345');
INSERT INTO gt_warehouse(
warehouse_id,
stock,
product_sku)
VALUES(
'178',
'',
'12345');
END;
ELSE
BEGIN
IF COALESCE((SELECT 1 FROM gt_warehouse WHERE product_sku = '12345' AND warehouse_id = '178' LIMIT 1), 0) THEN
BEGIN
UPDATE
gt_warehouse SET stock = ''
WHERE product_sku = '12345'
AND warehouse_id = '178';
END;
ELSE
BEGIN
INSERT INTO gt_warehouse(
warehouse_id,
stock,
product_sku)
VALUES (
'',
'',
'',
'12345');
END;
END IF;
END;
END IF;
Follow: You must do the following things to perform this task in MYSQL
1- you have use STORED PROCEDURE in MYSQL to set query block as package exactly as in SQL SERVER but syntax is bit different
CREATE DEFINER=`root`#`localhost` PROCEDURE `sp_report`(
------
------
)
BEGIN
--Query block with condition
END;
2- You don't need COALESCE to check the existence of value, you can simply use EXISTS (LIMIT is also optional)
IF EXISTS(SELECT 1 FROM gt_postmeta WHERE meta_value = '12345') THEN
3- After this you may get minor issues like proper use of semicolon, BEGIN & END which you can resolve by yourself.
I think this should work:
SELECT id, login, ( IF(requires='privacy-weight',0,privacy-weight) ) AS privacy-weight, requires
FROM [mytable]
WHERE [mywhereclause]
For more information on how the IF function works in MySQL see the docs at http://dev.mysql.com/doc/refman/5.5/en/if.html

MySQL Trigger - Where am I going wrong

Can someone tell me where I'm going wrong in creating this trigger in MySQL? Every time I try to create it, it keeps telling me there is an error.
USE `cl11-onestock`;
DELIMITER //
CREATE TRIGGER audit_insert
AFTER INSERT
ON stock_usage FOR EACH ROW
BEGIN
SET uUid = (SELECT UUID());
SET stockUsageId = (SELECT NEW.stock_usage_id);
SET siteId = (SELECT NEW.site_id);
SET date = (SELECT NEW.date);
SET patientName = (SELECT NEW.patient_name);
SET dentistDiscountId = (SELECT NEW.dentist_discount_id);
SET itemId = (SELECT NEW.item_id);
SET quantity = (SELECT NEW.quantity);
SET priceIncDiscount = (SELECT NEW.price_inc_discount);
SET vat = (SELECT NEW.vat);
SET priceIncVat = (SELECT NEW.price_inc_vat);
SET createdAt = (SELECT NEW.created_at);
SET updatedAt = (SELECT NEW.updated_at);
INSERT INTO stock_audit VALUES
(uUid, stockUsageId, siteId, date, patientName, dentistDiscountId, itemId, quantity, priceIncDiscount, vat, priceIncVat, createdAt, updatedAt);
END; //
DELIMITER ;
You need to use the keyword new to access the field values after insert and not like you are doing with select and you can use directly inside the insert query
So the trigger should be as
DELIMITER //
CREATE TRIGGER audit_insert
AFTER INSERT
ON stock_usage FOR EACH ROW
BEGIN
INSERT INTO stock_audit VALUES
(new.UUID, NEW.stock_usage_id, NEW.site_id, NEW.date, NEW.patient_name, NEW.dentist_discount_id, NEW.item_id, NEW.quantity, NEW.price_inc_discount, NEW.vat, NEW.price_inc_vat, NEW.created_at, NEW.updated_at);
END; //
DELIMITER ;

MYSQL Event IF then run query

What would be the proper way to do this? tried many things and searched everywhere online
CREATE EVENT myevent
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 5 DAYS
DO
BEGIN
SELECT CASE WHEN funded IS NULL OR funded = ''
THEN INSERT INTO mytable1 (`id`, `to`) VALUES (NULL, 'admin')
ELSE
FROM mytable2 WHERE id='$id';
END
Try like this
DECLARE xFounded varchar(10);
SELECT funded into xFounded FROM mytable2 WHERE id='$id';
if xFounded is null or xFounded ='' then
INSERT INTO mytable1 (`id`, `to`) VALUES (NULL, 'admin');
ELSE
// Do Else Part Here
end if;
This is probably the shorest way.
insert into mytable1 (`id`, `to`) VALUES (NULL, 'admin') on duplicate key update id=LAST_INSERT_ID(id), to=to;
select LAST_INSERT_ID();

Calling stored procedure sequentially from .sql file

I'm stuck here.
I've got a Procedure that I want to run X* times in a row. (*X is couple of thousands times)
The procedure based on input data does this:
1. Looks for an actions.id, if not found LEAVEs.
2. Looks for users.id, if not found, creates one and uses LAST_INSERT_ID();
3-5. Looks for summaries.id (3 types, total, daily and monthly), if not found, creates one and uses it's ID.
6. Once all required ids are collected, INSERTs new row into actions and either updates the summaries rows in a transaction, so if any fails - it does a ROLLBACK - no harm done.
7. Depending on the outcome SELECTs message.
CREATE PROCEDURE NEW_ACTION(
IN a_date TIMESTAMP,
IN u_name VARCHAR(255),
IN a_name VARCHAR(255),
IN a_chars INT,
IN url VARCHAR(255),
IN ip VARCHAR(15))
lbl_proc: BEGIN
DECLARE a_id, u_id, us_id, usd_id, usm_id, a_day, a_month, error INT;
DECLARE CONTINUE HANDLER FOR SQLSTATE '23000' SET error = 1;
SET error = 0;
SET a_day = DATE_FORMAT(SUBSTRING(a_date ,1,10), '%Y%m%d');
SET a_month = SUBSTRING(a_day, 1, 6);
/* 1. RETREIVING action.id */
SET a_id = (SELECT `id` FROM `actions` WHERE `name` = a_name);
IF a_id IS NULL THEN
SELECT 'error';
LEAVE lbl_proc;
END IF;
/* 2. RETREIVING users.id */
SET u_id = (SELECT `id` FROM `users` WHERE `name` = u_name);
IF u_id IS NULL THEN
INSERT INTO `users` (name) VALUES (u_name);
SET u_id = (SELECT LAST_INSERT_ID());
END IF;
/* 3. RETREIVING user_summaries.id */
SET us_id = (SELECT `id` FROM `users_summaries` WHERE `user_id` = u_id AND `action_id` = a_id);
IF us_id IS NULL THEN
INSERT INTO `users_summaries` (user_id, action_id) VALUES (u_id, a_id);
SET us_id = (SELECT LAST_INSERT_ID());
END IF;
/* 4. RETREIVING user_summaries_days.id */
SET usd_id = (SELECT `id` FROM `users_summaries_days` WHERE `day` = a_day AND `user_id` = u_id AND `action_id` = a_id);
IF usd_id IS NULL THEN
INSERT INTO `users_summaries_days` (day, user_id, action_id) VALUES (a_day, u_id, a_id);
SET usd_id = (SELECT LAST_INSERT_ID());
END IF;
/* 5. RETREIVING user_summaries_months.id */
SET usm_id = (SELECT `id` FROM `users_summaries_months` WHERE `month` = a_month AND `user_id` = u_id AND `action_id` = a_id);
IF usm_id IS NULL THEN
INSERT INTO `users_summaries_months` (month, user_id, action_id) VALUES (a_month, u_id, a_id);
SET usm_id = (SELECT LAST_INSERT_ID());
END IF;
/* 6. SAVING action AND UPDATING summaries */
SET autocommit = 0;
START TRANSACTION;
INSERT INTO `users_actions` (`date`, `user_id`, `action_id`, `chars`, `url`, `ip`) VALUES (a_date, u_id, a_id, a_chars, url, ip);
UPDATE `users_summaries` SET qty = qty + 1, chars = chars + a_chars WHERE id = us_id;
UPDATE `users_summaries_days` SET qty = qty + 1, chars = chars + a_chars WHERE id = usd_id;
UPDATE `users_summaries_months` SET qty = qty + 1, chars = chars + a_chars WHERE id = usm_id;
IF error = 1 THEN
SELECT 'error';
ROLLBACK;
LEAVE lbl_proc;
ELSE
SELECT 'success';
COMMIT;
END IF;
END;
Now, I've got raw data that I want to feed into this procedure. There's currently about 3000 rows.
I tried all the solutions I knew:
A. # mysql -uuser -ppass DB < calls.sql - Using php I've basically created a list of calls like this:
CALL NEW_ACTION('2010-11-01 13:23:00', 'username1', 'actionname1', '100', 'http://example.com/', '0.0.0.0');
CALL NEW_ACTION('2010-11-01 13:23:00', 'username2', 'actionname1', '100', 'http://example.com/', '0.0.0.0');
CALL NEW_ACTION('2010-11-01 13:23:00', 'username1', 'actionname2', '100', 'http://example.com/', '0.0.0.0');
...
This fails always (tried few times) at row 452 where it found two summary IDs (step 3).
I thought this could be due to the fact that earlier (rows 375-376) there are calls for the same user for the same action.
As if mysql didn't update tables in time, so the summary row created in CALL from line 375 isn't yet visible when line 376 gets executed - therefore creating another summary line.
Tought I'd try delaying calls...
B. Using mysql's SLEEP(duration).
This didn't change anything. Execution stops at the very same CALL again.
I'm out of ideas now.
Suggestions and help hugely appreciated.
NOTE: action names and user names repeat.
PS. Bear in mind this is one of my first procedures ever written.
PS2. Running mysql 5.1.52-community-log 64bit (Windows 7U), PHP 5.3.2 and Apache 2.2.17
EDIT
I've removed PHP related part of question to a separate question here.
EDIT2
Ok, I've deleted the first 200 calls from the .sql file. For some reason it went fine past the previous line that was stopping execution. Now it stopped at row 1618.
This would mean, that at one point a newly INSERTed summary row is no visible for a moment, therefore when it happens that one of the following iterations want to SELECT it, it's not yet accessible for them. Is that a MySQL bug?
EDIT3
Now there's another interesting thing I noticed. I investigated where two users_summaries get created. This happens (not always, but if, then it is) when there are two CALLs referring to the same user and action in close proximity. They could be next to each other or separated by 1 or 2 different calls.
If I move one of them (within .sql file) like 50-100 rows lower (executed earlier) than it's fine. I even managed to make the .sql file work as a whole. But this still doesn't really solve the problem. With 3000 rows it's not that bad, but if I had 100000, I'm lost. I can't rely on manual tweaks to .sql file.
This isn't really a solution, but a workaround.
Just to clarify, summary tables had id column as PRIMARY KEY with AUTO_INCREMENT option and indexes on both user_id and action_id column.
My investigation showed that although my procedure was looking for an entry that existed using WHERE user_id = u_id AND action_id = a_id in certain situations it didn't find it causing new row being inserted with the same user_id and action_id values - something I did not want.
Debugging the procedure showed that the summary row I was looking for, although not accessible with WHERE user_id = u_id AND action_id = a_id condition, was properly returned when calling it's id - PRIMARY KEY.
With this find I decided to change format of id column, from UNASIGNED INT with AUTO_INCEREMENT to a CHAR(32) which consisted of:
<user_id>|<action_id>
This meant that I knew exactly what the id of the row I wanted is even before it existed. This solved the problem really. It also enabled me to use INSERT ... ON DUPLICATE KEY UPDATE ... construct.
Below my updated procedure:
CREATE PROCEDURE `NEW_ACTION`(
IN a_date TIMESTAMP,
IN u_name VARCHAR(255),
IN a_name VARCHAR(255),
IN a_chars INT,
IN url VARCHAR(255),
IN ip VARCHAR(15))
SQL SECURITY INVOKER
lbl_proc: BEGIN
DECLARE a_id, u_id, a_day, a_month, error INT;
DECLARE us_id, usd_id, usm_id CHAR(48);
DECLARE sep CHAR(1);
DECLARE CONTINUE HANDLER FOR SQLSTATE '23000' SET error = 1;
SET sep = '|';
SET error = 0;
SET a_day = DATE_FORMAT(SUBSTRING(a_date ,1,10), '%Y%m%d');
SET a_month = SUBSTRING(a_day, 1, 6);
/* RETREIVING action.id */
SET a_id = (SELECT `id` FROM `game_actions` WHERE `name` = a_name);
IF a_id IS NULL THEN
SELECT 'error';
LEAVE lbl_proc;
END IF;
/* RETREIVING users.id */
SET u_id = (SELECT `id` FROM `game_users` WHERE `name` = u_name);
IF u_id IS NULL THEN
INSERT INTO `game_users` (name) VALUES (u_name);
SET u_id = LAST_INSERT_ID();
END IF;
/* SETTING summaries ids */
SET us_id = CONCAT(u_id, sep, a_id);
SET usd_id = CONCAT(a_day, sep, u_id, sep, a_id);
SET usm_id = CONCAT(a_month, sep, u_id, sep, a_id);
/* SAVING action AND UPDATING summaries */
SET autocommit = 0;
START TRANSACTION;
INSERT INTO `game_users_actions` (`date`, `user_id`, `action_id`, `chars`, `url`, `ip`)
VALUES (a_date, u_id, a_id, a_chars, url, ip);
INSERT INTO `game_users_summaries` (`id`, `user_id`, `action_id`, `qty`, `chars`)
VALUES (us_id, u_id, a_id, 1, a_chars)
ON DUPLICATE KEY UPDATE qty = qty + 1, chars = chars + a_chars;
INSERT INTO `game_users_summaries_days` (`id`, `day`, `user_id`, `action_id`, `qty`, `chars`)
VALUES (usd_id, a_day, u_id, a_id, 1, a_chars)
ON DUPLICATE KEY UPDATE qty = qty + 1, chars = chars + a_chars;
INSERT INTO `game_users_summaries_months` (`id`, `month`, `user_id`, `action_id`, `qty`, `chars`)
VALUES (usm_id, a_month, u_id, a_id, 1, a_chars)
ON DUPLICATE KEY UPDATE qty = qty + 1, chars = chars + a_chars;
IF error = 1 THEN
SELECT 'error';
ROLLBACK;
LEAVE lbl_proc;
ELSE
SELECT 'success';
COMMIT;
END IF;
END
Anyway, I still think there's some kind of a bug in MySQL, but I consider problem solved.