Created
January 27, 2024 22:04
-
-
Save FCO/455a9aa62d3d6740674d8b5e27c5c442 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" | |
' | |
SQL : BEGIN | |
BIND: [] | |
SQL : CREATE TABLE "transaction" ( | |
id integer NOT NULL primary key AUTOINCREMENT, | |
acc_from varchar(255) NOT NULL , | |
acc_to varchar(255) NOT NULL , | |
amount jsonb NOT NULL | |
) | |
BIND: [] | |
SQL : COMMIT | |
BIND: [] | |
SQL : BEGIN | |
BIND: [] | |
SQL : INSERT INTO "transaction"( | |
amount, | |
acc_to, | |
acc_from | |
) | |
VALUES( | |
?, | |
?, | |
? | |
) | |
BIND: ["\{\n \"currency\": \"BRL\",\n \"value\": 9.99\n}", 2, 1] | |
SQL : SELECT | |
"transaction".id , "transaction".acc_from as "acc-from", "transaction".acc_to as "acc-to", "transaction".amount | |
FROM | |
"transaction" | |
WHERE | |
_rowid_ = last_insert_rowid() | |
LIMIT 1 | |
BIND: [] | |
SQL : SELECT | |
"transaction".id , "transaction".acc_from as "acc-from", "transaction".acc_to as "acc-to", "transaction".amount | |
FROM | |
"transaction" | |
WHERE | |
"transaction".id = 1 | |
LIMIT 1 | |
BIND: [] | |
SQL : COMMIT | |
BIND: [] | |
SQL : SELECT | |
"transaction".id , "transaction".acc_from as "acc-from", "transaction".acc_to as "acc-to", "transaction".amount | |
FROM | |
"transaction" | |
WHERE | |
JSON_EXTRACT("transaction".amount, '$.currency') = 'BRL' | |
BIND: [] | |
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