0

我目前正在尝试将 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;
4

1 回答 1

1

我不熟悉 PostgreSQL,但查看您的代码示例,这里有一些评论:

  • $TG_OP = 'UPDATE': Perl 中的字符串比较是用eq操作符完成的
  • $OLD.user_id !== $NEW.user_id: 不等式的数值比较应该使用!=操作符来完成
  • null应该是undef
  • $userId = OLD.user_id:它似乎$OLD是一个对象(通过查看您的代码)?那么您可能应该user_id使用类似$OLD->user_id. .Javascript 中使用点运算符的所有其他属性访问也是如此;那些应该是->Perl 中的运算符。
  • NOTICE 'Update of user_id not allowed: %, at %'die: 你可以使用函数在 Perl 中抛出异常
  • IF... ELSE:在 Perl 中这是if...else
  • Math.max($cashOut - $bet, 0):在 Perl 中,您可以max从模块中使用List::Util
于 2020-01-28T11:08:39.867 回答