背景
有同学问在RDS MySQL 5.6在timestamp 设置为 not null 并且SQL模式是严格模式时,仍然可以插入空值,理论上应该有报错,是不是RDS的bug?
环境
MySQL 5.6 5.7 8.0,在RDS和自建数据库上都会遇到
现象
从上图中可以看到,在timestamp设置为not null时会自动补齐:
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
在客户的自建环境中timestamp类型没有自动补齐,在严格模式下会报错;
在RDS MySQL的环境中datetime类型没有自动补齐,,在严格模式下会报错:
溯源
If the explicit_defaults_for_timestamp system variable is disabled, TIMESTAMP columns by default are NOT NULL, cannot contain NULL values, and assigning NULL assigns the current timestamp. To permit a TIMESTAMP column to contain NULL, explicitly declare it with the NULL attribute. In this case, the default value also becomes NULL unless overridden with a DEFAULT clause that specifies a different default value. DEFAULT NULL can be used to explicitly specify NULL as the default value. (For a TIMESTAMP column not declared with the NULL attribute, DEFAULT NULL is invalid.) If a TIMESTAMP column permits NULL values, assigning NULL sets it to NULL, not to the current timestamp.
在explicit_defaults_for_timestamp值为OFF时,会自动补齐上文中的内容,而客户的环境里面explicit_defaults_for_timestamp是ON的,所以跟RDS MySQL结果有差异,跟客户说过后,验证就是explicit_defaults_for_timestamp值差异导致。
结论
每一件不合理的事情背后,必然有一个自己还未了解的合理原因.