浅谈数据库中的C
由来
一致性一致是个很有趣的话题, 在不同的上下文边界有不同的讨论点(e.g 分布式下会讨论最终一致性, 一致性Hash…etc)
本文结合Wikipedia中对数据库中的一致性描述浅谈数据中的一致性(本文对一致性术语的使用都特指数据库下的一致性)
何为数据库中的一致性
Wikipedia中对一致性的描述(定义A) :
Consistency in database systems refers to the requirement that any given database transaction must change affected data only in allowed ways. Any data written to the database must be valid according to all defined rules, including constraints, cascades, triggers, and any combination thereof. This does not guarantee correctness of the transaction in all ways the application programmer might have wanted (that is the responsibility of application-level code) but merely that any programming errors cannot result in the violation of any defined database constraints.
网络上的对一致性的定义B:
数据库的状态在事务执行后能从一个正确的状态迁移到另一个正确的状态
几个"潜台词"(Wikipedia):
- 使用事务 -> 实现一致性(而不是用一致性实现/满足事务)
- 数据库层面的一致性保证手段(constraints, cascades, triggers):
constraints : 约束, 比如字段不能NULL
cascades: 回滚的"多米诺效应", 客户端发送回滚指令回滚一系列相关事务
triggers: 在早期的MYSQL不多见(请见参考文献),监听一个事件类触发数据校验 - 数据库能保证事务的合法性
- 数据库不能保证事务的正确性 ->应用层保证
需要补充的是应用层检查+回滚 和 数据库约束保证(not null, unique…) 可能是本人见到的较为常见的用于保障一致性的场景
ACID原则中C是最终目的(A+I+D ->C)
参考:
https://en.wikipedia.org/wiki/Consistency_(database_systems)#cite_note-Date2012-1