2013-05-14 62 views
0

分析器錯誤我有我與SQL分析的更新語句::分析器如何捕捉SQL ::在Perl

uPdate scott.emp 
set ename='SCT%',emp_date=TO_DATE('04/16/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'),empno='15645' 
WHERE dept=20 and ename IN(select ename from emp where empno='1111'); 

但由於TO_DATE功能不能與SQL解析::分析器因此它拋出錯誤:

Incomplete SET clause! at ./post_audit.pl line 173 
Incomplete SET clause! at ./post_audit.pl line 173 

如何捕獲此類錯誤? eval能做到這一點嗎?沒有找到相同的適當文件。

代碼來解析SQL語句:

+12 use SQL::Parser; 

    +34 my $statement = "uPdate scott.emp set ename='SCT%',emp_date=TO_DATE('04/16/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'),empno='15645' WHERE dept=20 and ename IN(select ename from emp where empno='1111')"; 

    +172  my $parser = SQL::Parser->new('AnyData', {RaiseError=>1}); 
    +173  $parser->parse($statement); 

誤差在173線扔在解析的語句。

回答

1

我不認爲「TO_DATE」函數是錯誤的根源。

source code到SQL ::解析器模塊說:

my @sets = split /,/,$set_string; 
my(@cols,@vals); 
for(@sets) { 
    my($col,$val) = split/= /,$_; 
    return $self->do_err('Incomplete SET clause!') if !$col or !$val; 

注意 「=」 是由空間的正則表達式包圍:所以 「/ = /

,你應該空間環繞你的equals體徵:

set ename='SCT%' 

應該

set ename = 'SCT%' 

等等


至於處理它,這取決於其錯誤標誌您在構造函數中設置:

sub do_err { 
     ... 
     warn $err if $self->{"PrintError"}; 
     die if $self->{"RaiseError"}; 
     return undef; 
    } 
  • 如果設置RaiseError標誌,代碼將會死亡。

    my $parser = SQL::Parser->new('AnyData', {RaiseError=>1}); 
    

    因此,你需要用一個eval {}圍繞$parser->parse()呼叫,並檢查錯誤字符串[email protected]值。

  • 如果您設置了PrintError標誌,它會警告您。您可以通過捕獲警告信號來捕獲警告,如here on SOon PerlMaven所示。

  • 如果你沒有設置任何一個,你會從parse()得到「false」返回值,但不知道錯誤是什麼。

這是覆蓋在parse()POD if you check it

In addition to checking the return value of parse() with a variable like $success, you may use the PrintError and RaiseError attributes as you would in a DBI script:

  • If PrintError is true, then SQL syntax errors will be sent as warnings to STDERR (i.e. to the screen or to a file if STDERR has been redirected). This is set to true by default which means that unless you specifically turn it off, all errors will be reported.

  • If RaiseError is true, then SQL syntax errors will cause the script to die, (i.e. the script will terminate unless wrapped in an eval). This is set to false by default which means that unless you specifically turn it on, scripts will continue to operate even if there are SQL syntax errors.

+0

作爲一個側面說明,這聽起來是一個非常狡猾的方式來解析SQL。如果在SQL中的字符串文字中存在逗號或「=」,該怎麼辦? – DVK 2013-05-14 14:10:46

+0

DVK - 問題不在於我的SQL是否適合解析,問題是如何捕獲這些SQL並在解析任何不正確的SQL時輸出錯誤消息。 – contravaluebets 2013-05-15 10:36:41

+0

順便說一句,問題只是由於TO_DATE函數。當我解析下面的SQL時,它傳遞:'code'uPdate scott.emp set ename ='SCT%',emp_date = '04/16/2011',empno ='15645'WHERE dept = 20並且輸入IN從emp的where empno ='1111');'code' – contravaluebets 2013-05-15 10:44:24