在啟用二進制日誌(binlog)的 MySQL 環境中創建函數時,常遇到以下錯誤:
ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)
核心原因:MySQL 為了主從複製安全,要求函數聲明必須包含確定性特徵(DETERMINISTIC、NO SQL 或 READS SQL DATA),否則禁止創建。預設 log_bin_trust_function_creators = OFF 阻擋了未聲明特性的函數創建。
-- 查看當前狀態
SHOW VARIABLES LIKE 'log_bin_trust_function_creators';
-- 全局開啟
SET GLOBAL log_bin_trust_function_creators = 1;
-- 驗證
SHOW VARIABLES LIKE 'log_bin_trust_function_creators';
適用於臨時測試或無權修改配置文件的場景。
編輯 my.cnf(Linux)或 my.ini(Windows),在 [mysqld] 區塊添加:
[mysqld]
log-bin-trust-function-creators = 1
重啟 MySQL 服務使配置生效:
# Linux
systemctl restart mysqld
# Windows
net stop mysql && net start mysql
mysqld --log-bin-trust-function-creators=1
或在系統服務啟動腳本中添加該參數。
CREATE FUNCTION fn_example()
RETURNS INT
DETERMINISTIC
READS SQL DATA
BEGIN
-- 函數體
END;
-- 測試創建函數
CREATE FUNCTION test_func() RETURNS INT
DETERMINISTIC
RETURN 1;
-- 查看函數
SHOW CREATE FUNCTION test_func;
若無報錯即配置成功。建議配合 DETERMINISTIC 等特性聲明使用,兼顧功能與複製安全。