I am using PostgreSQL 9.6. I would like to create a new currency type extension on PostgreSQL that contains a string and a numerical value.
According to the documentation https://www.postgresql.org/docs/9.6/static/sql-createtype.html, I can use compose type directly in PostgreSQL, but this is not what I want because I want to be able to represent the type using a string and do casting. So the solution is to create a custom type such as the example "box" type. The documentation shows:
CREATE TYPE box;
CREATE FUNCTION my_box_in_function(cstring) RETURNS box AS ... ;
CREATE FUNCTION my_box_out_function(box) RETURNS cstring AS ... ;
CREATE TYPE box (
INTERNALLENGTH = 16,
INPUT = my_box_in_function,
OUTPUT = my_box_out_function
);
But it's not really helpful as to HOW to write such a function. Further search shows that function can only be written in C and shows example of simple type, not struct type.
So I basically want something like
typedef struct {
char code[4];
Numeric numeric;
} Currency
I want to use fixed type Numeric, that would avoid me the extra effort of implementing varlena header. Besides currency usually have fixed decimal point. I also want to be able to use the Numeric type internally because it allows me to reuse the function of Numeric.
How can I use Numeric, such that I can use a similar syntax as from PostgreSQL (e.g. Numeric(10,2)) to define my struct? Can I use the numeric_in function inside my currency_in function?