set client_min_messages = fatal;

set search_path = taggedtypes, public;

set client_encoding=latin9;

DROP TYPE currency CASCADE;
DROP TYPE currencyint CASCADE;
DROP TYPE currencyfloat CASCADE;
DROP TYPE currency_t CASCADE;
DROP TYPE currencyint_t CASCADE;
DROP TYPE currencyfloat_t CASCADE;
DROP TABLE currencies CASCADE;
DROP TABLE currency_test;

CREATE TABLE currencies (tag text, format text) WITH OIDS;

set client_min_messages = error;

copy currencies from stdin;
AUD	"AU$"999990.00
USD	"US$"999990.00
EUR	"¤  "999990.00
YEN	"   "999990.00"¥"
\.

SELECT create_tagged_type( 'currency', 'numeric(8,2)', 'currencies' );
SELECT create_tagged_type( 'currencyint', 'integer', 'currencies' );
SELECT create_tagged_type( 'currencyfloat', 'float', 'currencies' );

CREATE TABLE currency_test ( c1 currency, c2 currencyint, c3 currencyfloat );

copy currency_test from stdin;
232.44 USD	33 AUD	12 EUR
21.2 EUR	2 EUR	14 USD
-13.4444 AUD	-2 USD	-200 AUD
0.01 USD	2 AUD	23 USD
14.00 AUD	12 USD	1 USD
\.

CREATE FUNCTION print_currency( currency ) RETURNS text 
AS 'SELECT to_char( value($1), (tagdata($1)).format )' 
LANGUAGE 'sql' STRICT STABLE;

select create_tagged_operator( 'currency','*','numeric' ,'currency');
select create_tagged_operator( 'numeric', '*','currency','currency');
select create_tagged_operator( 'currency','/','currency','numeric' );
select create_tagged_operator( 'currency','/','numeric' ,'currency' );
select create_tagged_operator( 'currency','+','currency','currency');
select create_tagged_operator( 'currency','-','currency','currency');

--select create_tagged_operator( 'currencyint','*','integer'    ,'currencyint');
--select create_tagged_operator( 'integer',    '*','currencyint','currencyint');
--select create_tagged_operator( 'currencyint','/','currencyint','integer'    );
--select create_tagged_operator( 'currencyint','+','currencyint','currencyint');
--select create_tagged_operator( 'currencyint','-','currencyint','currencyint');

--select create_tagged_operator( 'currencyfloat','*','float'        ,'currencyfloat');
--select create_tagged_operator( 'float',        '*','currencyfloat','currencyfloat');
--select create_tagged_operator( 'currencyfloat','/','currencyfloat','float'        );
--select create_tagged_operator( 'currencyfloat','+','currencyfloat','currencyfloat');
--select create_tagged_operator( 'currencyfloat','-','currencyfloat','currencyfloat');

set client_min_messages = notice;

select tag(c1), sum( value(c1) ) from currency_test group by tag(c1) order by tag(c1);
select print_currency(c1), currency( value(c2), tag(c3) ) from currency_test where value(c1) > 5;
select a.c1*5, b.c1/5, a.c1+b.c1, a.c1-b.c1 from currency_test a, currency_test b where tag(a.c1) = tag(b.c1);
