KiKaDE: add uncompression
[nonametv.git] / tools / nonametv-populatedb
blob6cc4691f63b3427558ac1e0b6fd76e6c1308fbaa
1 #!/usr/bin/perl -w
3 use strict;
5 use FindBin;
6 use lib "$FindBin::Bin/../lib";
8 use File::Slurp;
10 use NonameTV;
11 use NonameTV::DataStore;
12 use NonameTV::Config qw/ReadConfig/;
14 use Getopt::Long;
15 use Text::CSV_XS;
17 my $opt = {
18 rebuild => 0,
21 my $res = GetOptions( $opt, qw/rebuild/ );
23 if( scalar( @ARGV ) != 2 )
25 print << 'EOHELP';
26 nonametv-populatedb [--rebuild] <data-directory> <country>
28 Populate the database with base data from files. Looks for data in
29 <data-directory>/ and <data-directory>/<country>/.
31 --rebuild Drop all tables and create them again. Note that this will
32 discard all data generated by Importers.
34 See also nonametv-dumpdb.
36 EOHELP
38 exit 1;
41 my( $datadir, $country ) = @ARGV;
43 # Read configuration
44 my $conf = ReadConfig();
46 my $ds = NonameTV::DataStore->new( $conf->{DataStore} );
48 if( $opt->{rebuild} ) {
49 print "Rebuilding database from $datadir/listings.sql\n";
50 my $commands = read_file( "$datadir/listings.sql" )
51 or die "Failed to read $datadir/listings.sql";
53 my @commands = split( /\s*;\s*/, $commands );
54 foreach my $command (@commands) {
55 $ds->sa->Sql( $command );
59 populate_table( $ds, "languagestrings", "$datadir/languagestrings.txt" );
60 populate_table( $ds, "channels", "$datadir/$country/channels.txt" );
61 populate_table( $ds, "trans_cat", "$datadir/$country/trans_cat.txt" );
63 sub populate_table {
64 my( $ds, $table, $file ) = @_;
66 print "Populating table $table from file $file\n";
68 $ds->sa->Delete( $table, {} );
70 if( not -f $file ) {
71 print "Skipping $table\n";
72 return;
75 my $in = new IO::File( "< $file" ) or die;
77 my $csv = Text::CSV_XS->new({eol=> "\n", 'binary' => 1});
79 my $sth;
81 while( my $row = $csv->getline($in) ) {
82 last if not defined $row->[0];
83 foreach (@{$row}) {
84 $_=undef if $_ eq '\N';
87 if( not defined( $sth ) ) {
88 my $params = join( ",", split( "", "?" x scalar( @{$row} ) ) );
90 $sth = $ds->sa->{dbh}->prepare( "insert into $table values ($params)" )
91 or die "Prepare failed.\nError: " . $ds->{dbh}->errstr;
94 $sth->execute( @{$row} ) or die "Execute failed: " . $ds->{dbh}->errstr;
97 $sth->finish();
99 $in->close();