在postgresql

时间:2015-08-26 13:47:53

标签: perl postgresql hash

我写了CGI script in perl。我同时从两个不同的位置收到POST request该脚本。 从POST请求我填充五个不同的表。我在每个POST请求中得到500行,然后我用100行填充每个表。

我的问题是,在一段时间后,一个或两个表开始显示较少的行数。这两个表都将ip存储在其中一列中。每次只有这两个表是缺少数据的表,这对我来说很奇怪。我无法理解为什么会这样。

虽然我在postgresql日志中收到了一些内容,但这些日志的数量与表中缺少的行数相同。

UTC STATEMENT:  insert into post (ip, count, location, source_server) values ($1, $2, $3, $4)
UTC STATEMENT:  insert into post (ip, count, location, source_server) values ($1, $2, $3, $4)
UTC STATEMENT:  insert into post (ip, count, location, source_server) values ($1, $2, $3, $4)

这是我的CGI代码。

use strict;
use warnings;
use CGI;
use DBI;
use JSON;


#Taking parameters passed as post request
my $conn = CGI->new;
my $data = $conn->param('POSTDATA');

#Details regarding database
my $host     = 'host';
my $user     = 'user';
my $password = 'password';
my $database = 'db';

my ( $location, $table, $entry );

#Creating connection to DB
my $dsn = "dbi:Pg:dbname=$database;host=$host";
my $dbh
    = DBI->connect( $dsn, $user, $password,
    { RaiseError => 0, PrintError => 0 } )
    or die("Connection to DB failed $!\n");

#Decoding json received in post request to perl hash
$data = decode_json $data;

my ($source_server) = keys %$data;

my $location = 'XX';

my $main_data = $$data{$source_server};

my @db      = qw /a b c d e/;
my %mapping = (
    'a'   => 'A',
    'b'     => 'B',
    'c' => 'C',
    'd' => 'D',
    'e'   => 'E'
);


foreach (@$main_data) {

    my $hash = $_;

    #Deciding which table data will be pushed into
    $table = shift @db;
    $entry = $mapping{$table};

    my $sth = $dbh->prepare(
        "insert into $table ($entry, count, location, source_server) values (?, ?, ?, ?)");

    while ( ( my $key, my $value ) = each %$hash ) {
        $sth->execute( $key, $value, $location, $source_server );

    }
    $sth->finish;

}

#Sending 200 status code back to client
print "Status: 200\n\n";

数据以{KEY : [{HASH},{HASH},{HASH},{HASH},{HASH}]}的形式传递给JSON中的CGI脚本。第二个和第五个哈希包含一段时间后缺少它的表的数据。

每个散列都有100个键:值对,因此总共有500个条目。

1 个答案:

答案 0 :(得分:0)

上面的simbabque评论之后我启用了RaiseErrorPrintError。在此之后我能够在服务器错误日志中收到错误。错误日志表明,由于同时插入来自多个地方的行,我得到主键违规,这导致了这种奇怪的行为。

我调整了我的主键,一切都很好:)