App-RecordStream
view release on metacpan or search on metacpan
lib/App/RecordStream/Operation/todb.pm view on Meta::CPAN
$this->{'DEBUG'} = $debug;
$this->{'FIELDS'} = $fields;
$this->{'DBH'} = App::RecordStream::DBHandle::get_dbh($args);
if ( $drop_table ) {
my $dbh = $this->{'DBH'};
eval {
$this->dbh_do( "DROP TABLE ".$dbh->quote_identifier($table_name));
};
}
$this->{'FIRST'} = 1;
}
sub accept_record {
my $this = shift;
my $record = shift;
if ( $this->{'FIRST'} ) {
$this->add_fields($record);
$this->create_table();
$this->{'FIRST'} = 0;
}
$this->add_row($record);
return 1;
}
sub add_fields {
my $this = shift;
my $record = shift;
my $fields = $this->{'FIELDS'};
return if ( scalar keys %$fields > 0 );
foreach my $key ( $record->keys() ) {
$fields->{$key} = 0;
}
}
sub add_row {
my $this = shift;
my $record = shift;
my $dbh = $this->{'DBH'};
my $name = $this->{'TABLE_NAME'};
my $fields = $this->{'FIELDS'};
$name = $dbh->quote_identifier($name);
my @keys = keys %$fields;
my $columns_string = join(',', map {$dbh->quote_identifier($_);} @keys);
my $values = '';
foreach my $key (@keys) {
my $value = ${$record->guess_key_from_spec($key)};
$value = '' if !defined($value);
$value = substr($value, 0, 255) if ( ! $fields->{$key} );
$values .= $dbh->quote($value) . ",";
}
chop $values;
my $sql = "INSERT INTO $name ($columns_string) VALUES ($values)";
$this->dbh_do($sql);
}
sub create_table {
my $this = shift;
my $dbh = $this->{'DBH'};
my $name = $this->{'TABLE_NAME'};
my $fields = $this->{'FIELDS'};
$name = $dbh->quote_identifier($name);
my $increment_name = 'AUTO_INCREMENT';
my $db_type = $dbh->get_info( 17 ); # SQL_DBMS_NAME
$increment_name = 'AUTOINCREMENT' if ( $db_type eq 'SQLite' );
my $sql = "CREATE TABLE $name ( id INTEGER PRIMARY KEY $increment_name, ";
foreach my $name (keys %$fields) {
my $type = $fields->{$name} || 'VARCHAR(255)';
$name = $dbh->quote_identifier($name);
$sql .= " $name $type,";
}
chop $sql;
$sql .= " )";
eval {
$this->dbh_do($sql);
};
}
sub add_help_types {
my $this = shift;
$this->use_help_type('keyspecs');
}
sub usage {
my $this = shift;
my $options = [
['drop', 'Drop the table before running create / insert commands.'],
['table', 'Name of the table to work with defaults to \'recs\''],
['debug', 'Print all the executed SQL'],
['key', 'Can either be a name value pair or just a name. Name value pairs should be fieldName=SQL Type. If any fields are specified, they will be the only fields put into the db. May be specified multiple times, may also be comma separated. T...
];
my $args_string = $this->options_string($options);
my $usage = <<USAGE;
__FORMAT_TEXT__
Recs to DB will dump a stream of input records into a database you specify.
( run in 2.378 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )