how i can convert a row inside a mysql/mariadb trigger into an json object with new JSON features?
BEGIN
CALL my_audit_insert(tableName, id, ... JSON_OBJECT(NEW) ...);
END
Is there any possibility to get programatically columns of NEW or OLD?
First Try - Create a Statement
Idea is to get colums from system tables and get each value from NEW/OLD programatically
BEGIN
SET @s = 'SELECT NEW.? INTO @result';
PREPARE stmt FROM @s;
SET @a = 'id';
EXECUTE stmt USING @a;
CALL audit_insert(NEW.id, 'pages', JSON_ARRAY(result));
END
(1336): Dynamic SQL is not allowed in stored function or trigger
Second Idea - Select the row via PrimaryKey as JSON_Object in after-triggers
procedure spGetJson from https://stackoverflow.com/a/35957518/7080961
DROP PROCEDURE IF EXISTS `spGetJson`;
DELIMITER //
CREATE DEFINER=`root`@`%` PROCEDURE `spGetJson`(pTableName varchar(45), pId int, out pJson JSON)
begin
select group_concat(concat("'", COLUMN_NAME, "', ", COLUMN_NAME) separator ',')
into @cols
from information_schema.columns
where TABLE_NAME = pTableName and TABLE_SCHEMA = database();
set @q = concat('select json_object(', @cols, ') INTO @a from ', pTableName);
if pId is not null then
set @q = concat(@q, ' where id = ', pId);
end if;
set @q = concat(@q, ';');
prepare statement from @q;
execute statement;
deallocate prepare statement;
SET pJson = @a;
end//
DELIMITER;
After Insert Trigger:
BEGIN
CALL spGetJson('pages', NEW.id, @a);
CALL audit_insert(NEW.id, 'pages', @a);
END
same: (1336): Dynamic SQL is not allowed in stored function or trigger
Conclusion:
- have to wait for this feature: https://bugs.mysql.com/bug.php?id=89366
- or switch to postresql