According the the documentation, MariaDB allows user defined functions to be used in generated column definitions https://mariadb.com/kb/en/generated-columns/
User-defined functions (UDFs) are supported in expressions for generated columns. However, MariaDB can't check whether a UDF is deterministic, so it is up to the user to be sure that they do not use non-deterministic UDFs with VIRTUAL generated columns.
I'm using MariaDB 10.3.20 and I've created a deterministic function but when trying to create the field, it fails. Here is some sample code.
CREATE TABLE `json_virt` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`json_arr` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ;
INSERT INTO json_virt SET json_arr = '["a","b"]' ;
INSERT INTO json_virt SET json_arr = '["c","d"]' ;
DELIMITER //
CREATE OR REPLACE FUNCTION `test`.`json_implode`(`data` TEXT, `sep` TEXT)
RETURNS text
CHARSET utf8mb4
COLLATE utf8mb4_unicode_ci
DETERMINISTIC
SQL SECURITY INVOKER
BEGIN
DECLARE i INT UNSIGNED DEFAULT 0 ;
DECLARE v_count INT UNSIGNED DEFAULT JSON_LENGTH(data) ;
DECLARE v_current_item BLOB DEFAULT NULL ;
DECLARE v_current_path BLOB DEFAULT NULL ;
DECLARE sep_length INT UNSIGNED DEFAULT CHAR_LENGTH(sep) ;
DECLARE str TEXT DEFAULT '' ;
WHILE i < v_count DO
SET v_current_path = CONCAT('$[', i, ']') ;
SET v_current_item = JSON_EXTRACT(data, v_current_path) ;
SET v_current_item = JSON_UNQUOTE(v_current_item) ;
SET str = CONCAT(str, sep, v_current_item) ;
SET i := i + 1;
END WHILE;
SET str = SUBSTRING(str, sep_length+1) ;
RETURN str ;
END //
DELIMITER ;
SELECT
json_virt.*,
json_implode(json_virt.json_arr, ', ') AS json_imp
FROM json_virt
;
ALTER TABLE `json_virt` ADD `json_str` TEXT AS (json_implodex(json_arr, ', ')) VIRTUAL ;
ALTER TABLE `json_virt` ADD `json_str1` TEXT AS json_implode('["x","y"]', ', ') VIRTUAL ;
The json_implode() function works nicely as you can see by the SELECT statement, but when trying to do the last two ALTER TABLE statements, both fail.
I'm interested in this from a few different angles:
- Why doesn't this work?
- What is an example of a UDF that will work for a generated column definition?
- Is it possible to use multi-line or more complex code in a generated column definition?
- Is there a better way accomplish what I'm trying to do (Take a field that is a JSON array and implode it so each item is separated by a comma as a string)?