Skip to content

Commit 44787c9

Browse files
committed
feat: add minus operator for money_with_currency
1 parent 6b9cb6f commit 44787c9

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
defmodule Algora.Repo.Migrations.DefineMinusOperator do
2+
use Ecto.Migration
3+
4+
def up do
5+
execute("""
6+
CREATE OR REPLACE FUNCTION money_sub(money_1 money_with_currency, money_2 money_with_currency)
7+
RETURNS money_with_currency
8+
IMMUTABLE
9+
STRICT
10+
LANGUAGE plpgsql
11+
SET search_path = ''
12+
AS $$
13+
DECLARE
14+
currency varchar;
15+
subtraction numeric;
16+
BEGIN
17+
IF currency_code(money_1) = currency_code(money_2) THEN
18+
currency := currency_code(money_1);
19+
subtraction := amount(money_1) - amount(money_2);
20+
return row(currency, subtraction);
21+
ELSE
22+
RAISE EXCEPTION
23+
'Incompatible currency codes for - operator. Expected both currency codes to be %', currency_code(money_1)
24+
USING HINT = 'Please ensure both columns have the same currency code',
25+
ERRCODE = '22033';
26+
END IF;
27+
END;
28+
$$;
29+
""")
30+
|> Money.Migration.adjust_for_type(repo())
31+
32+
execute("""
33+
CREATE OPERATOR - (
34+
leftarg = money_with_currency,
35+
rightarg = money_with_currency,
36+
procedure = money_sub,
37+
commutator = -
38+
);
39+
""")
40+
|> Money.Migration.adjust_for_type(repo())
41+
end
42+
43+
def down do
44+
execute("DROP OPERATOR IF EXISTS - (none, money_with_currency);")
45+
46+
execute("DROP FUNCTION IF EXISTS money_sub(money_with_currency, money_with_currency);")
47+
end
48+
end

0 commit comments

Comments
 (0)