Handling state management for an opaque-type state

Register the opaque data type in the database with the CREATE OPAQUE TYPE statement.

After you register the opaque data type, the database server can obtain information about the data type of the state value when the CREATE FUNCTION statement registers the function signatures of the aggregate support functions.

You need to write the opaque-type support functions only if you need such functionality in the aggregate support functions. For example, the input and output support functions might be useful when you debug your UDA. If you do write opaque-type support functions, you must compile and link them into a shared-object module, as Compile a C UDR describes.

Register the aggregate support functions with the CREATE FUNCTION statement.

Specify the registered opaque type as the data type of the state parameters and return values in the function signatures of the aggregate support functions.

The database server can perform memory management for an opaque-type state because it can determine the size of the opaque data type. The CREATE OPAQUE TYPE statement registers the opaque type, including its size, in the system catalog tables of the database. From the system catalog tables, the database server can determine the size of the aggregate state to allocate. Therefore, you do not need to allocate the opaque-type state in the INIT support function.

In the ITER function, you can initialize or update an opaque-type state in either of the following ways:
  • In-place state update

    To modify the state, change the values in the internal opaque-type structure that the database server has passed into the ITER function as an argument.

  • Allocate a new state

    To modify the state, allocate PER_ROUTINE memory for a new internal opaque-type structure and put the new values into this structure.

    If you need to initialize the internal structure of the opaque type, the INIT or ITER function can allocate PER_ROUTINE memory for the structure perform the appropriate initializations. When the support function exits, the database server copies the contents of this PER_ROUTINE structure into the PER_COMMAND system-allocated state buffer.

For more information, see When to allocate and deallocate a state. For an example of a user-defined aggregate that uses an opaque-type state, see the description of the PERCENT_GTR aggregate in The PERCENT_GTR user-defined aggregate.