如何在PL / SQL中创建枚举类型?

时间:2011-12-14 06:51:28

标签: plsql

例如,我想创建自己的布尔类型并将其命名为Bool。我该怎么做?

或红绿灯的类型,即其中只有红色,黄色,绿色(当然为空)。

4 个答案:

答案 0 :(得分:8)

我不认为 A.B.Cade 提供的解决方案是完全正确的。我们假设这样的程序:

procedure TestEnum(enum_in lights);

enum_in的价值是多少?红色?黄色?绿色?

我提出另一个解决方案。这是包示例

CREATE OR REPLACE PACKAGE pkg_test_enum IS

  SUBTYPE TLight IS BINARY_INTEGER RANGE 0..2;
  Red CONSTANT TLight := 0;
  Yellow CONSTANT TLight := 1;
  Green CONSTANT TLight := 2;

  --get sting name for my "enum" type
  FUNCTION GetLightValueName(enum_in TLight) RETURN VARCHAR2;

  PROCEDURE EnumTest(enum_in TLight);

END pkg_test_enum;


CREATE OR REPLACE PACKAGE BODY pkg_test_enum IS 
  FUNCTION GetLightValueName(enum_in TLight) 
  RETURN VARCHAR2
  IS
    ResultValue VARCHAR2(6);
  BEGIN
    CASE enum_in 
      WHEN Red THEN ResultValue := 'Red';
      WHEN Green THEN ResultValue := 'Green';
      WHEN Yellow THEN ResultValue := 'Yellow';
      ELSE ResultValue := '';
    END CASE;
    RETURN ResultValue;
  END GetLightValueName;


  PROCEDURE EnumTest(enum_in TLight)
  IS
  BEGIN
    --do stuff
    NULL;
  END EnumTest;
END pkg_test_enum;

我现在可以在不同的包中使用TLight。我现在可以针对预定义值测试enum_in或null。

这是用法示例

begin
  pkg_test_enum.EnumTest(pkg_test_enum.Red);
end;

此外,你可以使这种类型不可为空。

SUBTYPE TLight IS BINARY_INTEGER RANGE 0..2 NOT NULL;

答案 1 :(得分:4)

This blog describes a way to do it using constant values

除了常量之外,博客还定义了有效颜色的子类型。

SQL> declare
  2  RED constant number(1):=1;
  3  GREEN constant number(1):=2;
  4  BLUE constant number(1):=3;
  5  YELLOW constant number(1):=4;
  6  --
  7  VIOLET constant number(1):=7;
  8  --
  9  subtype colors is binary_integer range 1..4;
 10  --
 11  pv_var colors;
 12  --
 13  function test_a (pv_var1 in colors) return colors
 14  is
 15  begin
 16     if(pv_var1 = YELLOW) then
 17             return(BLUE);
 18     else
 19             return(RED);
 20     end if;
 21  end;
 22  --

答案 2 :(得分:4)

我能想到的最接近的想法是:

create or replace type lights as object
(
  red varchar2(8),
  yellow varchar2(8),
  green varchar2(8),
constructor function lights return self as result
)

和身体:

create or replace type body lights is
constructor function lights return self as result is
begin
  self.red = 'red';
  self.yellow = 'yellow';
  self.green = 'green';
  return;
end;
end;

然后在代码中你可以使用它:

declare
l lights := new lights;
begin
   dbms_output.put_line(l.red);
end;

答案 3 :(得分:0)

我以前使用的方法与@mydogtom和@klas-lindbäck相同。我在尝试刷新内存时发现了这一点。但是,@ a-b-cade建议的对象方法让我开始思考。我同意@mydogtom所描述的问题(值是多少?),但让我想到使用对象是可能的。

我想到的是一种方法,该方法使用具有单个成员属性的对象作为枚举的值,并对每个可能的值使用静态函数。我看不到如何与子类型结合使用以对值字段进行真正的限制,而不是正式将其设置为非空。但是,我们可以在构造函数中对其进行验证。与“适当的”枚举(例如,在Java中)相比,该功能的不利之处在于我们无法阻止某个人直接将val属性更新为无效值。但是,只要人们使用构造函数和set_value函数,它都是安全的。我不确定开销(在创建对象和维护对象等方面的运行时)是否值得,因此我可能会继续使用@mydogtom描述的方法,但是不确定。

您也可以将名称作为属性并在set_value中进行设置(有点像@ ab-cade的版本),但这会添加另一个可以直接更新的属性,因此还有一组状态,其中val和名称不匹配,因此我更喜欢名称为函数的方法。

(使用下面的我的demo_enum类型)的示例用法是

procedure do_stuff(enum in demo_enum) is
begin
   if enum.eqals(demo_enum.foo()) then
      -- do something
   end if;
end do_stuff;

procedure do_stuff(enum1 in demo_enum, enum2 in demo_enum) is
begin
   if enum1.eqals(enum2) then
      -- do something
   end if;
end do_stuff;

我所做的是定义一个基类,并在其中尽可能多:实际的val字段,用于静态值的equals函数,set_valueto_string功能。同样是name函数,但是这只是被覆盖(无法看到如何正式地将成员函数抽象化,因此基本版本只会引发异常)。我也使用name作为检查该值是否有效的方法,以减少需要枚举可能值的位数

create or replace type enum_base as object(
    -- member field to store actual value
    val integer,

    -- Essentially abstract name function
    -- Should be overridden to return name based on value
    -- Should throw exception for null or invalid values
    member function name return varchar2,

    --
    -- Used to update the value.  Called by constructor
    --
    member procedure set_value(pvalue in integer),
    
    --
    -- Checks the current value is valid
    -- Since we can't stop someone updating the val property directly, you can supply invalid values
    --
    member function isValid return boolean,
    
    --
    -- Checks for equality with integer value 
    -- E.g. with a static function for a possible value:   enum_var.equals( my_enum_type.someval() )
    --    
    member function equals(other in integer) return boolean,
        
    --
    -- For debugging, prints out name and value (to get just name, use name function)
    --      
    member function to_string return varchar2
    
    
) not instantiable not final;
/

create or replace type body enum_base is

    member function name return varchar2 is
    begin
        -- This function must be overriden in child enum classes.
        -- Can't figure out how to do an abstract function, so just throw an error
        raise invalid_number;
    end;
    
    member procedure set_value(pvalue in integer) is
        vName varchar2(3);
    begin
        self.val := pvalue;
        -- call name() in order to also validate that value is valid
        vName := self.name;                          
    end set_value;
    
            
    member function isValid return boolean is
        vName varchar2(3);
    begin
        begin
            -- call name() in order to also validate that value is valid
            vName := self.name;   
            return true; 
        exception
            when others then
                return false;
        end;            
    end isValid;
    
    
    member function equals(other in integer) return boolean is
    begin
        return self.val = other;
    end equals;
    
    member function to_string return varchar2 is
    begin 
        if self.val is null then
            return 'NULL';
        end if;

        return self.name || ' (' || self.val || ')';
    end to_string;
end;
/

在实际的枚举类中,我必须定义一个构造函数(仅调用set_value)并重写name函数以为每个可能的值返回一个名称。然后,我为每个可能的值定义一个静态函数,该函数返回该值的整数索引。最后,我定义了equals的重载,该重载与相同类型的另一个枚举进行比较。如果要将其他属性附加到每个值,则可以通过定义其他函数来实现。

create or replace type demo_enum under enum_base (
            
    -- Note: the name of the parameter in the constructor MUST be the same as the name of the variable.  
    -- Otherwise a "PLS-00307: too many declarations" error will be thrown when trying to instanciate
    -- the object using this constructor         
    constructor function demo_enum(val in integer) return self as result,
    
    --
    -- Override name function from base to give name for each possible value and throw 
    -- exception for null/invalid values
    --
    overriding member function name return varchar2,
    
    --
    -- Check for equality with another enum object
    --  
    member function equals(other in demo_enum) return boolean,

    
    --
    -- Define a function for each possible value
    --
    static function foo return integer,
    static function bar return integer
        
) instantiable final;
/

create or replace type body demo_enum is
    
    constructor function demo_enum(val in integer) return self as result is        
    begin   
        self.set_value(val);        
        return;     
    end demo_enum;
    
    
    overriding member function name return varchar2 is
    begin
        if self.val is null then
            raise invalid_number;
        end if;
        
        case self.val
            when demo_enum.foo() then
                return 'FOO';
            when demo_enum.bar() then
                return 'BAR';
            else 
                raise case_not_found; 
        end case;
    end;    
        
    member function equals(other in demo_enum) return boolean is
    begin
        return self.val = other.val;
    end equals;
            
    static function foo return integer is
    begin 
        return 0;
    end foo;
    
    static function bar return integer is
    begin 
        return 1;
    end bar;    

end;
/

可以测试。我定义了两组测试。一个是针对该特定枚举的一组手动测试,还说明了用法:

--
-- Manual tests of the various functions in the enum
--
declare
    foo demo_enum := demo_enum(demo_enum.foo());
    alsoFoo demo_enum := demo_enum(demo_enum.foo());
    bar demo_enum := demo_enum(demo_enum.bar());
    
    vName varchar2(100);    
    
    procedure assertEquals(a in varchar2, b in varchar2) is
    begin
        if a <> b then
            raise invalid_number;
        end if;
    end assertEquals;
    
    procedure assertEquals(a in boolean, b in boolean) is
    begin
        if a <> b then
            raise invalid_number;
        end if;
    end assertEquals;
    
    procedure test(vName in varchar2, enum in demo_enum, expectFoo in boolean) is
    begin
        dbms_output.put_line('Begin Test of ' || vName);
        if enum.equals(demo_enum.foo()) then
            dbms_output.put_line(vName || ' is foo');
            assertEquals(expectFoo, true);
        else
            dbms_output.put_line(vName || ' is not foo');
            assertEquals(expectFoo, false);
        end if;
        
        if enum.equals(demo_enum.bar()) then
            dbms_output.put_line(vName || ' is bar');
            assertEquals(expectFoo, false);
        else
            dbms_output.put_line(vName || ' is not bar');
            assertEquals(expectFoo, true);
        end if;
                
        if enum.equals(foo) then
            dbms_output.put_line(vName || '.equals(vFoo)');
            assertEquals(expectFoo, true);
        else
            assertEquals(expectFoo, false);
        end if;
        
        if expectFoo then
            assertEquals(enum.name, 'FOO');
        else
            assertEquals(enum.name, 'BAR');
        end if;
        
        assertEquals(enum.isValid, true);
        
        case enum.val
            when demo_enum.foo() then
                dbms_output.put_line(vName || ' matches case foo');
            when demo_enum.bar() then
                dbms_output.put_line(vName || ' matches case bar');
            else
                dbms_output.put_line(vName || ' matches no case!!!');
        end case;
        
        dbms_output.put_line(vName || ': ' || enum.to_string());
        dbms_output.put_line('--------------------------------------------------');
        dbms_output.put_line('');
    end test;
begin    
    test('foo', foo, true);
    test('bar', bar, false);
    test('alsoFoo', alsoFoo, true);
        
    
    foo.val := -1;
    assertEquals(foo.isValid, false);    
    begin
        vName := foo.name;    
    exception
        when case_not_found then
            dbms_output.put_line('Correct exception for fetching name when invalid value: ' || sqlerrm);
    end;
    
    foo.val := null;
    assertEquals(foo.isValid, false);    
    begin
        vName := foo.name;    
    exception
        when invalid_number then
            dbms_output.put_line('Correct exception for fetching name when null value: ' || sqlerrm);
    end;
end;

另一个稍微自动化一些,可以用于继承enum_base的任何枚举(只要它不添加其他函数-如果有人,则无法找到仅查找静态函数的方法知道让我知道)。这将检查您是否错误地将相同的整数值定义为多个可能的值静态函数:

--
-- generated test that no two values are equal 
--
declare
    vSql varchar2(4000) := '';
    
    typename constant varchar2(20) := 'demo_enum';
    
    cursor posvals is   
        select procedure_name
        from user_procedures
        where object_name = upper(typename)
          and procedure_name not in (upper(typename), 'EQUALS', 'NAME');

    cursor posvals2 is   
        select procedure_name
        from user_procedures
        where object_name = upper(typename)
          and procedure_name not in (upper(typename), 'EQUALS', 'NAME');


    procedure addline(line in varchar2) is
    begin
        vSql := vSql || line || chr(10);
    end;
begin
    addline('declare');
    addline('   enum ' || typename || ';');
    addline('begin');
        
    for posval in posvals loop    
        addline('   enum := ' || typename || '(' || typename || '.' || posval.procedure_name || '());');    
        for otherval in posvals2 loop
            addline('   if enum.equals(' || typename || '.' || otherval.procedure_name || '()) then');
            if otherval.procedure_name = posval.procedure_name then                 
                addline('      dbms_output.put_line(''' || otherval.procedure_name || ' = ' || posval.procedure_name || ''');');
            else
                addline('      raise_application_error(-20000, ''' || otherval.procedure_name || ' = ' || posval.procedure_name || ''');');
            end if;
            addline('   else');
            if otherval.procedure_name = posval.procedure_name then                 
                addline('      raise_application_error(-20000, ''' || otherval.procedure_name || ' != ' || posval.procedure_name || ''');');
            else
                addline('      dbms_output.put_line(''' || otherval.procedure_name || ' != ' || posval.procedure_name || ''');');
            end if;
            addline('   end if;');
        end loop;        
        addline('');
    end loop;
    addline('end;');
    
    execute immediate vSql;
end;