如何防止表被清空

來源:互聯網
上載者:User

一般來說,我們未來阻止使用者刪除或者清空表以及資料, 可以直接從許可權下手,給他少量的許可權即可。 
比如,防止使用者進行truncate 操作, 可以給如下許可權:

t_girl=# create role ytt3 with login connection limit 1  password 'ytt3';    CREATE ROLEt_girl=# alter schema ytt owner to ytt3;ALTER SCHEMAt_girl=# grant select on all tables in schema ytt to ytt3;GRANT




現在用新使用者ytt3登陸並且執行TRUNCATE,發現被禁止。
bash-4.1$ psql -U ytt3 t_girlpsql (9.3.4)Type "help" for help.t_girl=> truncate table j2;ERROR:  permission denied for relation j2





但是當測試的時候,一般來說,管理員為了方便懶得去分配各種各樣細的許可權。 那麼,我們在建立表的時候, 就得給這張表來做對應的限制。當然了,生產環境不建議這麼做。
這個實現就比較簡單了,建立一個基於語句的觸發器就OK了。
t_girl=# \sf prevent_truncateCREATE OR REPLACE FUNCTION public.prevent_truncate() RETURNS trigger LANGUAGE plpgsqlAS $functio$BEGINRAISE EXCEPTION 'Prevent "%"  to be truncated!', TG_TABLE_SCHEMA||TG_TABLE_NAME;RETURN NEW;END;$function$




t_girl=# \d j2        Table "ytt.j2" Column |  Type   | Modifiers --------+---------+----------- id     | integer |  str2   | text    | Triggers:    trigger_truncate_before BEFORE TRUNCATE ON j2 FOR EACH STATEMENT EXECUTE PROCEDURE ytt.prevent_truncate()

 

t_girl=# truncate table j2;ERROR:  Prevent "ytt.j2"  to be truncated!



這種方法也只是對於提供了這項功能的資料庫才OK。 比如MySQL的觸發器只提供了基於行的操作,那麼語句的操作就不能觸發了。 所以如果在MySQL上來實現這點,就比較麻煩。要麼,就從許可權入手,
mysql> truncate table j2;ERROR 1142 (42000): DROP command denied to user 'ytt3'@'localhost' for table 'j2'


要麼,就對資料庫的操作用SPROC封裝起來,
+------------------------------------+| Error                              |+------------------------------------+| Prevent t_girl.j2 to be truncated! |+------------------------------------+1 row in set (0.00 sec)


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.