init_script.sql 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. -- 字符脱敏处理
  2. SET GLOBAL log_bin_trust_function_creators = 1;
  3. CREATE
  4. FUNCTION text_mask(text varchar(100), head_len int, tail_len int)
  5. RETURNS varchar(100)
  6. BEGIN
  7. DECLARE t_len, m_len, mid_len int;
  8. DECLARE ret varchar(100);
  9. SET t_len = LENGTH(text);
  10. IF t_len = 0 THEN
  11. SET ret = '';
  12. ELSEIF t_len = 1 THEN
  13. SET ret = text;
  14. ELSEIF t_len = 2 THEN
  15. SET ret = CONCAT(LEFT(text, 1), '*');
  16. ELSE
  17. SET m_len = head_len + tail_len;
  18. IF m_len < t_len THEN
  19. SET ret = CONCAT(LEFT(text, head_len), REPEAT('*', t_len - m_len), RIGHT(text, tail_len));
  20. ELSEIF m_len = t_len THEN
  21. SET ret = CONCAT(LEFT(text, CASE WHEN head_len > 0 THEN head_len - 1 ELSE head_len END), '*', RIGHT(text, CASE WHEN head_len > 0 AND tail_len > 0 THEN tail_len ELSE tail_len - 1 END));
  22. ELSEIF head_len > t_len THEN
  23. SET ret = CONCAT(LEFT(text, t_len - 1), '*');
  24. ELSEIF tail_len > t_len THEN
  25. SET ret = CONCAT('*', RIGHT(text, t_len - 1));
  26. ELSE
  27. SET mid_len = CEIL(t_len / 2);
  28. SET ret = CONCAT(LEFT(text, mid_len - 1), REPEAT('*', t_len - (mid_len - 1) * 2), RIGHT(text, mid_len - 1));
  29. END IF;
  30. END IF;
  31. RETURN ret;
  32. END;
  33. SET GLOBAL log_bin_trust_function_creators = 0;