Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle: specifying default value for object type column

I have an object type with no-args constructor, but when I specify it as default value for a column of that type, I get ORA-00904: invalid identifier error.

Example:

CREATE OR REPLACE TYPE test_t AS OBJECT
(
  val      NUMBER(10),
  CONSTRUCTOR FUNCTION test_t return self as result
)

CREATE OR REPLACE TYPE BODY test_t AS 
  CONSTRUCTOR FUNCTION test_t RETURN SELF AS RESULT IS
  BEGIN
    val := 1;
    RETURN;
  END;
END;

CREATE TABLE test_table (
    test_attr test_t DEFAULT new test_t()
)

Error: ORA-00904: "INKA"."TEST_T"."TEST_T": invalid identifier

If I replace DEFAULT with e.g. test_t(1), it works, but that sort of breaks the OO encapsulation paradigm, I want all fields of same type to have same default "default values" (hope you know what I mean :-)

Am I missing something here, or is this normal and it is not possible to use non-default constructors like this?

like image 296
Marin Bonacci Avatar asked Mar 29 '12 13:03

Marin Bonacci


People also ask

What is the default value for an object of type object?

The default(object) is a way to null. This is asking the C# compiler to add the default value of the object type, which is null. So why not simply say null there?

How do you set a default value of a column in a table in Oracle?

A column can be given a default value using the DEFAULT keyword. The DEFAULT keyword provides a default value to a column when the Oracle INSERT INTO statement does not provide a specific value. The default value can be literal value, an expression, or a SQL Function, such as SYSDATE.

What clause allows you to specify a default value for a column?

Use the DEFAULT clause in the CREATE TABLE statement to specify the default value for the database server to insert into a column when no explicit value for the column is specified. This syntax fragment is part of the Column definition.


1 Answers

Looks like this is not possible.

One workaround would be to use a trigger:

CREATE OR REPLACE TRIGGER test_trigger
  BEFORE INSERT OR UPDATE
ON test_table
  FOR EACH ROW
WHEN ( new.test_attr IS NULL )
BEGIN
  :new.test_attr := NEW test_t();
END test_trigger;
/

It does not completely ignore non-default constructors by the way, overriding the default constructor

CONSTRUCTOR FUNCTION test_t(in_val NUMBER)
RETURN SELF AS RESULT

leads to an exception when trying to define the table with DEFAULT NEW test_t(1):

ORA-06553: PLS-307: too many declarations of 'TEST_T' match this call

like image 81
Peter Lang Avatar answered Nov 15 '22 00:11

Peter Lang