停止没有架构限定符的SQL语句

时间:2015-10-19 20:50:16

标签: oracle plsql

如果SQL语句缺少模式限定符,如何阻止它运行?大多数这些问题都是由开发过程捕获的,但有没有办法阻止那些漏掉这些问题?

例如,此语句应该有效:

create table jheller.test_table(a number);

此声明应失败:

create table test_table(a number);

在开发过程中很容易发现大多数这些问题。通常缺少权限会导致ORA-00942: table or view does not exist之类的错误。或者,如果语句在错误的模式上成功运行,则会导致在测试期间捕获的明显错误。

但不可避免的是,一些不好的陈述仍然会进入升级到高层环境的部署中。这导致在SYS等模式中创建的部署和无效对象损坏。 (我们不应该像SYS那样进行如此多的部署,但这是我们无法控制的。)

没有必要抓住100%的这些问题。但是,捕获99.9%而不是99%会产生显着差异。

1 个答案:

答案 0 :(得分:1)

可以通过以下方式阻止没有架构限定符的SQL语句:

  1. 在所有数据库上创建虚假的空架构。
  2. 创建数据库触发器以防止在该架构中创建对象。
  3. 在部署脚本开头将会话变量CURRENT_SCHEMA设置为该架构。
  4. 安装 - 每个数据库运行一次。

    --Create a user.  It won't be used so lock it and don't grant it any privileges.
    create user schema_qualifier_required identified by "[SOME RANDOM PASSWORD HERE]";
    alter user schema_qualifier_required account lock;
    
    --Create trigger to prevent any other user from creating objects on it.
    create or replace trigger schema_qualifier_required.no_objects_on_schema_qualifier
    before ddl on database
    /*
    Purpose: SCHEMA_QUALIFIER_REQUIRED exists only to help prevent statements
      without schema qualifiers.  This trigger ensures no objects can be created in
      the schema.
    
    Run this command in a session to help ensure schema qualifiers are used:
      alter session set current_schema=schema_qualifier_required;
    
    To drop or modify the schema this trigger must be dropped like this:
      alter system set "_system_trig_enabled"=false;
      drop trigger schema_qualifier_required.no_objects_on_schema_qualifier
      alter system set "_system_trig_enabled"=true;
    */
    begin
        if ora_dict_obj_owner = 'SCHEMA_QUALIFIER_REQUIRED' then
            raise_application_error(-20000, 'You cannot create objects in this schema.  '||
                'Did you forget to use a schema qualifier in your statement?');
        end if;
    end;
    /
    

    非合格报表最初有效。

    SQL> create table test1(a number);
    
    Table created.
    
    SQL> select * from test1;
    
    no rows selected
    

    ALTER SESSION以防止将来运行不合格的语句。

    SQL> alter session set current_schema=schema_qualifier_required;
    
    Session altered.
    

    不合格的陈述不再有效。

    SQL> create table test2(a number);
    create table test2(a number)
    *
    ERROR at line 1:
    ORA-00604: error occurred at recursive SQL level 1
    ORA-20000: You cannot create objects in this schema.  Did you forget to use a
    schema qualifier in your statement?
    ORA-06512: at line 3
    
    SQL> select * from test1;
    select * from test1
                  *
    ERROR at line 1:
    ORA-00942: table or view does not exist
    

    我还没有在生产中使用过这种方法。如果有人发现这种方法存在问题或者知道更好的方法,请编辑,评论或添加其他答案。