sub _open_db {
my $conn = $Server->CreateObject("adodb.connection");
$conn->Open($ScriptingNamespace->GetConnectionString);
return $conn;
}
sub _db_command {
my ($conn,$sql) = @_;
my $cmd = $Server->CreateObject("adodb.command");
$cmd->{ActiveConnection} = $conn;
$cmd->{CommandText} = $sql;
$cmd->{Prepared} = 1;
$cmd->Parameters->Refresh;
return $cmd;
}
sub _import_products {
my ($fnm) = @_;
chomp $fnm;
return unless my $fh = _open_file($fnm);
my $csv = Text::CSV_XS->new;
my $line = <$fh>;
$csv->parse($line);
my @fields = $csv->fields;
my %map;
return if _check_fields([qw(PRODUCTID)], \@fields, \%map);
my $conn = _open_db;
my $cmd = _db_command($conn,"set nocount off;select * from products where productid=?");
my $cmd2 = _db_command($conn,"exec fixup_generic_names ?");
while (defined($line = <$fh>)) {
if (!defined($csv->parse($line))) {
_append_log("Malformed CSV file at line $.");
return;
}
@fields = $csv->fields;
$cmd->Parameters(0)->{Value} = $fields[$map{PRODUCTID}];
my $rs = $Server->CreateObject("adodb.recordset");
$rs->Open($cmd,undef,adOpenStatic,adLockPessimistic);
if ($rs->{EOF}) {
_append_log("Product $fields[$map{PRODUCTID}] not found
");
} else {
my $pid = $rs->Fields('ProductID')->{Value};
for (qw(list of product table column names)) {
$rs->Fields($_)->{Value} = $fields[$map{$_}] if exists $map{$_};
}
$rs->Update;
if (_report_errors($conn)) {
_append_log("Current product id $pid (update)
");
$conn->Errors->Reset;
next;
}
undef $rs;
$cmd2->Parameters(0)->{Value} = $pid;
my $cnt = Variant(VT_R8|VT_BYREF, 0);
$cmd2->Execute($cnt);
if (_report_errors($conn)) {
_append_log("Current product id $pid (fixup)
");
$conn->Errors->Reset;
next;
}
}
}
_append_log("Done");
}