postgresql , 10.0 , 主動防禦 , 是否允許執行不帶where條件的update\delete
你是否曾經被不帶where 條件的sql誤傷過呢?
比如
update tbl set amount=amount-100 where id=?;
缺少where條件,就變成了
update tbl set amount=amount-100;
正常情況下,這樣的sql不應該在業務邏輯中出現。通常出現在sql注入,又或者誤操作中。
如果你真的不小心執行了,那麼全表的資料都會被删除或者更新,最快的恢複手段是flash back query,postgresql中,可以使用xlog,生成undo,比如将xlog_level設定為logical,同時表的match必須設定為記錄full old value。
那麼就有方法從xlog中生成undo,flash back該表。
flashback query屬于被動防禦的話,資料庫有沒有主動防禦措施呢?
postgresql提供了一個機制,允許你設定參數
+bool allow_empty_deletes = true;
+bool allow_empty_updates = true;
進而允許是否能執行不帶where 條件的update或delete.
這個參數可以設定為全局、會話級、使用者級、庫級、或者事務級别。
設定後,你就能控制是否允許執行不帶條件的update,delete了。
其實不帶where條件的update, delete還不夠全面。比如where 1=1或者where true,都需要防範。
還有我們甚至可以設定百分比(比如百分之多少的記錄被update,delete時,或者超過多少記錄被dml後,回退整個事務)
通過postgresql提供的鈎子可以完成以上功能。
這個patch的讨論,詳見郵件組,本文末尾url。
postgresql社群的作風非常嚴謹,一個patch可能在郵件組中讨論幾個月甚至幾年,根據大家的意見反複的修正,patch合并到master已經非常成熟,是以postgresql的穩定性也是遠近聞名的。
<a href="https://commitfest.postgresql.org/12/948/">https://commitfest.postgresql.org/12/948/</a>
<a href="https://www.postgresql.org/message-id/flat/[email protected]#[email protected]">https://www.postgresql.org/message-id/flat/[email protected]#[email protected]</a>
<a href="https://www.postgresql.org/message-id/attachment/45216/training_wheels_001.patch">https://www.postgresql.org/message-id/attachment/45216/training_wheels_001.patch</a>