SELECT LAST_INSERT_ID() Not working with BIGINT on MySQL 5.6.11 When Using a Trigger

StackOverflow https://stackoverflow.com/questions/17495460

  •  02-06-2022
  •  | 
  •  

Вопрос

I'm posting a new question following my previous post "SELECT LAST_INSERT_ID() Not working with BIGINT on MySQL 5.6.11"

In any case, after further investigation I found that the LAST_INSERT_ID() was not working because I had a trigger BeforeInsert on the table that I had a problem with.

So basically my problem is when calling LAST_INSERT_ID() after the INSERT statement it returns 0, because I have a BeforeInsert as a Trigger on this table. If I comment out this Trigger, it works fine and the LAST_INSERT_ID() gives me the correct number.

Any ideas how to over come this problem ? Below is the trigger

DELIMITER $$

USE `mydb`$$

CREATE
DEFINER=`root`@`%`
TRIGGER `mydb`.`Booking_BINS`
BEFORE INSERT ON `mydb`.`Booking`
FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one

BEGIN

DECLARE iNextBookingId INT;
SET iNextBookingId = (SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE     TABLE_SCHEMA=DATABASE() AND TABLE_NAME='Booking');
SET NEW.BookingId = iNextBookingId; 

INSERT INTO AuditTrail  (AuditTrailId,UserId,ActionType,TableName,RowKey,FieldName,OldValue,NewValue,LoggedOn) VALUES
(UUID(),NEW.LastChangedBy,'INSERT','Booking',NEW.BookingId,'HotelId',NULL,NEW.HotelId,NOW()),
(UUID(),NEW.LastChangedBy,'INSERT','Booking',NEW.BookingId,'AgentId',NULL,NEW.AgentId,NOW()),
(UUID(),NEW.LastChangedBy,'INSERT','Booking',NEW.BookingId,'SupplierId',NULL,NEW.SupplierId,NOW());


 END$$
Это было полезно?

Решение

You're creating a race condition by assuming INFORMATION_SCHEMA.TABLES.AUTO_INCREMENT can be used as NEW.BookingId. As soon as you have more than one session firing this trigger concurrently, you'll run into trouble because both sessions will try to assign the same value to BookingId.

Also, auditing inserts in a BEFORE trigger is risky because the insert could fail for a variety of reasons, and then you might get phantom audit data.

You should move your auditing into an AFTER trigger. That way you know that the INSERT succeeded, and the auto-incremented BookingId will have been generated in the conventional way.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top