import rows into MongoDB
[mongodb-experiments.git] / dbi2mongo.pl
1 #!/usr/bin/perl -w
2
3 sub BEGIN {
4 $ENV{DBI_AUTOPROXY}='dbi:Gofer:transport=stream;url=ssh:dpavlin@koha.ffzg.hr';
5 }
6
7 use strict;
8 use DBI;
9 use MongoDB;
10 use Data::Dump qw/dump/;
11
12 $|++;
13
14 my $debug = @ARGV ? 1 : 0;
15
16 our $dbi = "DBI:mysql:database=test";
17 our ( $dbi, $user, $password );
18 our ( $database, $collection ) = ( 'test', 'test' );
19
20 our $sql = qq{
21         select
22                 id as _id,
23                 table.*
24         from table
25         where id > ?
26         order by id asc
27         limit 100000
28 };
29
30 require 'config.pl';
31
32 warn "# $dbi $user -> $database $collection\n";
33
34 my $conn = MongoDB::Connection->new;
35 my $db   = $conn->get_database( $database );
36 my $coll = $db->get_collection( $collection );
37 my $dbh  = DBI->connect($dbi,$user,$password,{ RaiseError => 1 });
38
39 $db->drop if $debug;
40
41 # > db.items.find().sort({item_id:-1}).limit(1);
42 my $last = $coll->query()->sort({ '_id' => -1 })->limit(1)->next;
43 warn dump( $last );
44 my $last_id = $last->{_id} || 0;
45
46 print "Fetching items from $dbi _id > $last_id\n";
47
48 my $sth = $dbh->prepare($sql);
49 $sth->execute( $last_id );
50
51 warn dump( $sth->{NAME} );
52
53 print "found ",$sth->rows," items to process...\n";
54
55 while (my $row = $sth->fetchrow_hashref() ) {
56
57         map { $row->{$_} * 1 } grep { defined $row->{$_} && $row->{$_} =~ /^\d+$/ } keys %$row;
58         $coll->insert( $row );
59 }
60