Created
January 27, 2024 22:02
-
-
Save FCO/558d0e32ed620e0a6cee6799141e0f36 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ raku -I. -MRed -MRed::Type -MRed::AST::Value -MJSON::Fast -e ' | |
red-defaults "SQLite"; | |
#my $*RED-DEBUG = True; | |
enum Currency <USD GBP BRL>; | |
class Money { has Rat() $.value; has Currency() $.currency } | |
class DBMoney does Red::Type { | |
method inflator { -> $_ is copy --> Money { given .&from-json { Money.new: :value(.<value>), :currency(Currency::{ .<currency> }) } } } | |
method deflator { -> Money $_ { to-json %( value => .value, currency => .currency ) } } | |
method red-type-column-type { "jsonb" } | |
method red-type-accepts(Money) { True } | |
method red-type-db-methods { | |
role :: { | |
method value { | |
Red::AST::Cast.new: Red::AST::JsonItem.new(self, ast-value "value"), "numeric" | |
} | |
method currency { | |
Red::AST::Cast.new: Red::AST::JsonItem.new(self, ast-value "currency"), "text" | |
} | |
} | |
} | |
} | |
model Transaction { has $.id is serial; has $.acc-from is column; has $.acc-to is column; has DBMoney $.amount is column } | |
schema(Transaction).create; | |
Transaction.^create: :1acc-from, :2acc-to, :amount(Money.new: :value(9.99), :currency(BRL)); | |
.say for Transaction.^all.grep: *.amount.currency eq "BRL" | |
' | |
Transaction.new(id => 1, acc-from => "1", acc-to => "2", amount => Money.new(value => 9.99, currency => Currency::BRL)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment