我目前正在尝试将 PostgreSQL 函数从 JS 转换为 Perl,因为PLV8扩展在我的环境中不可用。
我拥有的原始JS/PLV8代码是:
CREATE OR REPLACE FUNCTION plays_users_stats_trigger()
RETURNS trigger AS $$
if (TG_OP === 'UPDATE' && OLD.user_id !== NEW.user_id)
throw new Error('Update of user_id not allowed');
var userId, gross = 0, net = 0, num = 0;
var bet, cashOut, bonus;
// Add new values.
if (NEW) {
userId = NEW.user_id;
bet = NEW.bet;
bonus = NEW.bonus || 0;
cashOut = NEW.cash_out || 0;
gross += Math.max(cashOut - bet, 0) + bonus;
net += (cashOut - bet) + bonus;
num += 1;
}
// Subtract old values
if (OLD) {
userId = OLD.user_id;
bet = OLD.bet;
bonus = OLD.bonus || 0;
cashOut = OLD.cash_out || 0;
gross -= Math.max(cashOut - bet, 0) + bonus;
net -= (cashOut - bet) + bonus;
num -= 1;
}
var sql =
'UPDATE users ' +
' SET gross_profit = gross_profit + $1, ' +
' net_profit = net_profit + $2, ' +
' games_played = games_played + $3 ' +
' WHERE id = $4';
var par = [gross,net,num,userId];
plv8.execute(sql,par);
$$ LANGUAGE plv8;
然而,作为 Perl 的新手,我正在努力获得正确的功能,我目前的代码是:
CREATE OR REPLACE FUNCTION plays_users_stats_trigger() RETURNS trigger AS $$
if($_TD->{event} = 'UPDATE' && $_TD->{old}{i}->user_id != $_TD->{new}{i}->user_id) {
die('Update of user_id not allowed: %, at %',$_TD,now());
}
my $userId = undef;
my $gross = 0;
my $net = 0;
my $num = 0;
my $bet = undef;
my $cashOut = undef;
my $bonus = undef;
if($OLD) {
$userId = $OLD->user_id;
$bet = $OLD->bet;
$bonus = $OLD->bonus || 0;
$cashOut = $OLD->cash_out || 0;
$gross -= max($cashOut - $bet, 0) + $bonus;
$net -= ($cashOut - $bet) + $bonus;
$num -= 1;
} elsif($NEW) {
$userId = $NEW->user_id;
$bet = $NEW->bet;
$bonus = $NEW->bonus || 0;
$cashOut = $NEW->cash_out || 0;
$gross += max($cashOut - $bet, 0) + $bonus;
$net += ($cashOut - $bet) + $bonus;
$num += 1;
}
$sql = 'UPDATE users SET gross_profit = gross_profit + $1, net_profit = net_profit + $2, games_played = games_played + $3 WHERE id = $4';
spi_exec_prepared($sql, [$gross, $net, $num, $userId]);
$$ LANGUAGE plperl;