]> git.sesse.net Git - remoteglot/blob - ingest.pl
Switch from flat files to PostgreSQL.
[remoteglot] / ingest.pl
1 #! /usr/bin/perl
2
3 # To ingest old data into the database.
4
5 use strict;
6 use warnings;
7 use DBI;
8 use DBD::Pg;
9 use JSON::XS;
10 use Tie::Persistent;
11
12 my $dbh = DBI->connect('dbi:Pg:dbname=remoteglot');
13 $dbh->{AutoCommit} = 0;
14 $dbh->{RaiseError} = 1;
15
16 # Import positions from history.
17 for my $filename (<www/history/*.json>) {
18         $filename =~ m#www/history/(.*)\.json#;
19         my $id = $1;
20         print "Analysis: $id...\n";
21
22         my $contents;
23         {
24                 local $/ = undef;
25                 open my $fh, "<", $filename
26                         or die "$filename: $!";
27                 $contents = <$fh>;
28                 close $fh;
29         }
30
31         #$dbh->do('INSERT INTO analysis VALUES (?)', undef, $contents);
32
33         my $json = JSON::XS::decode_json($contents);
34         if (defined($json->{'plot_score'})) {   
35                 my $engine = $json->{'id'}{'name'} // die;
36                 my $depth = $json->{'depth'} // 0;
37                 my $nodes = $json->{'nodes'} // 0;
38
39                 $dbh->do('DELETE FROM scores WHERE id=?', undef, $id);
40                 $dbh->do('INSERT INTO scores (id, plot_score, short_score, engine, depth, nodes) VALUES (?, ?, ?, ?, ?, ?)',
41                         undef, $id, $json->{'plot_score'}, $json->{'short_score'}, $engine, $depth, $nodes);
42         }
43 }
44
45 # Import clock information.
46 tie my %clock_info_for_pos, 'Tie::Persistent', 'clock_info.db', 'rw';
47
48 while (my ($id, $clock_info) = each %clock_info_for_pos) {
49         print "Clock: $id...\n";
50         $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
51         $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)',
52                 undef, $id, $clock_info->{'white_clock'}, $clock_info->{'black_clock'},
53                 $clock_info->{'white_clock_target'}, $clock_info->{'black_clock_target'});
54 }
55
56 $dbh->commit;
57