Optimize insert by preparing once and execute many times

tags/0.1.1
Daniel Berteaud 12 years ago
parent 585d7d027c
commit 7306a25db2
  1. 33
      root/usr/bin/samba-db-logd

@ -67,10 +67,24 @@ sub mysql_escape {
return $string; return $string;
} }
# Prepare query once
sub prepare_query {
my $dbh = shift;
my $q = "INSERT INTO audit ".
"(samba_host,date_day,date_time,username,client_ip,client_name,".
"action,access_mode,status,share,file_src,file_dst)".
"VALUES(?,?,?,?,?,?,?,?,?,?,?,?);";
my $qh = $dbh->prepare($q);
return $qh;
}
my $dbh = db_connect; my $dbh = db_connect;
my $qh = prepare_query($dbh);
# Open log file # Open log file
printlog("opening log file") if ($opts{debug} ge 1); printlog("opening log file") if ($opts{debug} ge 1);
my $tail = File::Tail->new(name=>$opts{log}, maxinterval=>15); my $tail = File::Tail->new(name=>$opts{log}, maxinterval=>15);
while (defined(my $line=$tail->read)){ while (defined(my $line=$tail->read)){
@ -125,7 +139,6 @@ while (defined(my $line=$tail->read)){
# MySQL escape # MySQL escape
# Shouldn't be needed, but just in case logs contains junk # Shouldn't be needed, but just in case logs contains junk
$username = mysql_escape($username); $username = mysql_escape($username);
$client_ip = mysql_escape($client_ip); $client_ip = mysql_escape($client_ip);
$client_name = mysql_escape($client_name); $client_name = mysql_escape($client_name);
@ -149,21 +162,9 @@ while (defined(my $line=$tail->read)){
printlog($msg); printlog($msg);
} }
my $q = "INSERT INTO audit ". $qh->execute($host,$date,$time,$username,$client_ip,$client_name,$action,
"(samba_host,date_day,date_time,username,client_ip,client_name,". $access_mode,$status,$share,$file_src,$file_dst) ||
"action,access_mode,"; die "Database error: ".$qh->errstr;
$q .= "status,share,file_src";
$q .= ",file_dst" if (defined $file_dst);
$q .= ") VALUES('$host','$date','$time','$username','$client_ip','$client_name',".
"'$action','$access_mode'";
$q .= ",'$status','$share','$file_src'";
$q .= ",'$file_dst'" if (defined $file_dst);
$q .= ")";
printlog("Current query:\n$q\n") if ($opts{debug} ge 3);
my $qh = $dbh->prepare($q);
$qh->execute or exit(1);
} }
exit(0); exit(0);

Loading…
Cancel
Save