Annotation of db/prgsrc/updatedb.pl, revision 1.29

1.1       boris       1: #!/usr/local/bin/perl 
                      2: 
                      3: =head1 NAME
                      4: 
                      5: updatedb.pl - a script for creation of new database. 
                      6: 
                      7: =head1 SYNOPSIS
                      8: 
1.25      roma7       9: updatedb.pl B<[-i]> I<file1> I<file2>....
1.1       boris      10: 
                     11: 
                     12: =head1 DESCRIPTION
                     13: 
                     14: Updates information in the B<chgk> databse. Uses file
                     15: 
1.25      roma7      16: =head1 OPTIONS
                     17: 
                     18: =item B<-i> 
                     19: 
                     20: Ask about ParentId. 
                     21: 
1.1       boris      22: 
                     23: =head1 BUGS
                     24: 
                     25: The database, user and password are hardcoded. 
                     26: 
                     27: =head1 AUTHOR
                     28: 
                     29: Dmitry Rubinstein
                     30: 
1.29    ! roma7      31: =head1 $Id: updatedb.pl,v 1.28 2002/11/11 09:57:49 roma7 Exp $
1.1       boris      32: 
                     33: =cut
                     34: 
1.25      roma7      35: use vars qw($opt_i);
                     36: 
                     37: use Getopt::Std;
                     38: getopts('i');
1.29    ! roma7      39: #open STDERR, ">errors";
1.25      roma7      40: my $Interactive=$opt_i || 0;
                     41: 
                     42: 
1.1       boris      43: my (%RevMonths) = 
1.5       boris      44:     ('Jan', '1', 'Feb', '2', 'Mar', '3', 'Apr', '4', 'May', '5', 'Jun', '6',
                     45:      'Jul', '7', 'Aug', '8', 'Sep', '9', 'Oct', '10', 'Nov', '11',
                     46:      'Dec', '12', 
                     47:      'JAN', '1', 'FEB', '2', 'MAR', '3', 'APR', '4', 'MAY', '5', 'JUN', '6',
                     48:      'JUL', '7', 'AUG', '8', 'SEP', '9', 'OCT', '10', 'NOV', '11',
                     49:      'DEC', '12', 
1.13      boris      50:      'Янв', '1', 'Фев', '2', 'Мар', '3', 'Апр', '4', 'Май', '5',
                     51:      'Июн', '6', 'Июл', '7', 'Авг', '8', 'Сен', '9', 
                     52:      'Окт', '10', 'Ноя', '11', 'Дек', '12');
1.1       boris      53: my ($sth);
                     54: 
1.13      boris      55: 
1.3       boris      56: 
1.4       boris      57: 
1.3       boris      58: 
1.1       boris      59: use DBI;
                     60: use strict;
1.28      roma7      61: my $isunsorted=0;
1.1       boris      62: sub UpdateParents {
1.5       boris      63:     my ($dbh, $ParentId, $all_qnum) = @_;
                     64:     if ($ParentId) {
                     65:        my ($sth1) = $dbh->prepare("SELECT QuestionsNum, ParentId 
                     66: FROM Tournaments WHERE Id = $ParentId");
                     67:        $sth1->execute;
                     68:        my ($q, $p) = ($sth1->fetchrow)[0, 1];
                     69:        $dbh->do("UPDATE Tournaments SET 
                     70:                   QuestionsNum=$q + $all_qnum 
                     71:                   WHERE Id = $ParentId");
                     72:        &UpdateParents($dbh, $p, $all_qnum);
                     73:     }
1.1       boris      74: }
                     75: 
                     76: sub getField {
1.5       boris      77:     my($desc, $dbh) = @_;
                     78:     my($key);
                     79:     my($value) = ('');
                     80:     while (<$desc>) {
1.11      boris      81:        s/[
]//g;
1.5       boris      82:        if ($key && /^\s*$/) {
                     83:            chomp $value;
1.24      roma7      84:             $value =~ s/\s+$//;
1.5       boris      85:            chomp $key;
                     86:            if ($key eq 'Дата') {
                     87:                $value =~ s/^(.*)-(.*)-(.*)$/$3-$2-$1/;
1.20      boris      88:                my($month) = $RevMonths{$2} || '01';
                     89:                $value =~ s/-(.*)-/-$month-/;
                     90:                $value =~ s/-00*$/-01/;
1.5       boris      91:            }
                     92:            $value = $dbh->quote($value);
                     93:            return ($key, $value);
                     94:        }
                     95:        next if (/^\s*$/);
                     96:        
1.16      boris      97:        if (!$key && /^(.*?)[:\.]\s*(.*)$/s) {
1.5       boris      98:            $key = $1;
1.16      boris      99:            $value=$2;
1.5       boris     100:            next;
1.1       boris     101:        }
1.5       boris     102:        if ($key) {
                    103:            $value .= $_;
                    104:            next;
1.1       boris     105:        }
1.5       boris     106:     }
                    107:     if ($key && $value) {
1.23      roma7     108:         $value=~s/\s+$//;
1.5       boris     109:        $value = $dbh->quote($value);
                    110:        return ($key, $value);
                    111:     }
                    112:     return (0, 0);
1.1       boris     113: }
                    114: 
                    115: sub SelectGroup {
1.7       boris     116:     my ($dbh, $source, $TourName) = @_;
                    117:     my ($sth, $ParentId, $i, @arr);
1.25      roma7     118: 
                    119:     if ($Interactive) {    
                    120:        $sth = $dbh->prepare("SELECT Id, Title FROM
1.1       boris     121:                Tournaments WHERE Type = 'Г'");
1.25      roma7     122:        $sth->execute;
                    123:        print "Выберите группу для турнира:\n$TourName, файл $source\n\n";
                    124:        while (@arr=$sth->fetchrow) {
                    125:                print "[$arr[0]] $arr[1]\n";
                    126:        }
                    127:        $ParentId = <STDIN>;
                    128:        chomp $ParentId;
                    129:        if (!$ParentId) {
                    130:                print "Пропускаем файл $source\n";
                    131:                print STDERR "Файл $source отвергнут оператором\n";
                    132:                return (0,0);
                    133:        } else {
                    134:                print "Вы выбрали турнир: $ParentId\n";
                    135:                $sth = $dbh->prepare("INSERT INTO Tournaments
                    136:                              (Title, Type, ParentId, FileName) 
                    137:                               VALUES ($TourName, 'Ч', $ParentId, 
                    138:                                        $source)");
                    139:                $sth->execute;
                    140:                my $TournamentId = $sth->{mysql_insertid};
                    141:                return ($TournamentId,$ParentId);
                    142:        }
1.7       boris     143:     } else {
1.25      roma7     144: # Теперь, если файла нет в дереве турниров, никаких вопросов не 
                    145: # задаётся, а вместо этого он добавляется в группу 9999
                    146:        $ParentId = 9999;
1.27      roma7     147:                print UNSORTED "$source\n";     
                    148:                $isunsorted=1;
1.25      roma7     149:                $sth = $dbh->prepare("INSERT INTO Tournaments
1.7       boris     150:                              (Title, Type, ParentId, FileName) 
                    151:                               VALUES ($TourName, 'Ч', $ParentId, 
1.8       boris     152:                                        $source)");
1.25      roma7     153:                 $sth->execute;
                    154:                my $TournamentId = $sth->{mysql_insertid};
                    155:                return ($TournamentId,$ParentId);
                    156:        }
1.7       boris     157:                
                    158:     
1.1       boris     159: }
                    160: 
                    161: sub UpdateTournament {
1.5       boris     162:     my ($dbh, $TournamentId, $field, $value) = @_;
                    163:     $dbh->do("UPDATE Tournaments SET $field=$value WHERE Id=$TournamentId")
                    164:        or die $dbh->errstr;
1.1       boris     165: }
                    166: 
                    167: sub UpdateQuestion {
1.5       boris     168:     my ($dbh, $QuestionId, $field, $value) = @_;
                    169:     $dbh->do("UPDATE Questions SET $field=$value 
1.1       boris     170:                WHERE QuestionId=$QuestionId")
1.5       boris     171:        or die $dbh->errstr;
1.1       boris     172: }
                    173: 
1.7       boris     174: sub CheckFile {
1.10      boris     175:     my ($dbh, $source, $title) = @_;
1.7       boris     176:     my $sth = $dbh->prepare("SELECT Id,ParentId,QuestionsNum FROM Tournaments
                    177:                              WHERE FileName=$source AND Type='Ч'");
                    178:     $sth->execute or die $dbh->errstr;
                    179:     my @arr = $sth->fetchrow;
                    180:     if (! scalar @arr) {
                    181:        return SelectGroup($dbh,$source,$title);
                    182:     }
                    183:     my($Id,$ParentId,$QuestionsNum)=@arr;
1.10      boris     184:     if($QuestionsNum) {        
1.7       boris     185:        print "Файл $source с данными $title уже существует. ",
                    186:        "Заменить?[y/N]\n";
                    187:        my $answer = <STDIN>;
                    188:        if ($answer !~ /^[yY]/) {
                    189:            return (0,0);
                    190:        } else {
1.10      boris     191:            DeleteTournament($dbh,$Id,$ParentId,$QuestionsNum,0);
1.7       boris     192:        }
                    193:     } 
                    194:     return($Id,$ParentId);     
                    195: }
                    196: 
                    197: 
                    198: sub DeleteTournament {
1.10      boris     199:     my ($dbh,$Id,$ParentId,$QuestionsNum,$DeleteMyself) = @_;
                    200:     if ($QuestionsNum) {
                    201:        UpdateParents($dbh,$ParentId,-$QuestionsNum);
                    202:     }
1.7       boris     203:     my (@Tours) = &GetTours($dbh, $Id);
                    204:     foreach my $Tour (@Tours) {
1.12      boris     205:        DeleteTournament($dbh,$Tour,$Id,0,1);
1.7       boris     206:     }
                    207:     my $sth = $dbh->prepare("DELETE FROM Questions
                    208:                              WHERE ParentId=$Id");
                    209:     $sth->execute or die $dbh->errstr;
                    210:     if($DeleteMyself) {
                    211:        $sth = $dbh->prepare("DELETE FROM Tournaments
                    212:                              WHERE Id=$Id");
1.9       boris     213:        $sth->execute or die $dbh->errstr;
1.7       boris     214:     }
                    215: }
1.8       boris     216: 
                    217: sub GetTours {
                    218:        my ($dbh, $ParentId) = @_;
                    219:        my (@arr, @Tours);
                    220: 
                    221:        my ($sth) = $dbh->prepare("SELECT Id FROM Tournaments
                    222:                WHERE ParentId=$ParentId ORDER BY Id");
                    223: 
                    224:        $sth->execute;
                    225: 
                    226:        while (@arr = $sth->fetchrow) {
                    227:                push @Tours, $arr[0];
                    228:        }
                    229: 
                    230:        return @Tours;
                    231: }
                    232: 
1.13      boris     233: sub CreateTour {
1.17      boris     234:     my ($dbh,$title,$ParentId,$TourNum,$rh_defaults)=@_;
1.13      boris     235:     my $sth = $dbh->prepare("INSERT INTO Tournaments
1.18      boris     236:                             (Title, Type, ParentId, Number) 
1.17      boris     237:                             VALUES ($title, 'Т', $ParentId, $TourNum)");
1.13      boris     238:     $sth->execute;
                    239:     my $TourId = $sth->{mysql_insertid};
                    240:     while (my ($key,$value)=each %$rh_defaults) {
                    241:        &UpdateTournament($dbh, $TourId, $key, $value);
                    242:     }
                    243:     return $TourId;
                    244: }
                    245:                
1.8       boris     246: 
1.1       boris     247: MAIN: 
                    248: {
1.5       boris     249:     my($key, $value, $addition);
1.13      boris     250:     #
                    251:     # Inherited fields for a Tour or Tournament
                    252:     #
                    253:     my %TourFields = ('Копирайт' => 'Copyright',
                    254:                      'Инфо' => 'Info', 'URL' => 'URL',
                    255:                      'Ссылка' => 'URL', 'Редактор' => 'Editors',
                    256:                      'Обработан'=> 'EnteredBy',
                    257:                      'Дата'=>'PlayedAt');
                    258:     #
                    259:     # Inherited fields for a Question
                    260:     #
                    261:     my %QuestionFields = ('Тип'=> 'Type', 'Вид'=> 'Type', 
1.15      boris     262:                          'Автор' => 'Authors', 'Рейтинг'=>'Rating', 
1.21      boris     263:                          'Источник' => 'Sources',
                    264:                          'Тема' => 'Topic');
1.13      boris     265:                          
                    266:                      
1.5       boris     267:     my($source);
                    268:     
                    269:     my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")
                    270:        or die "Can't connect to DB chgk\n";
1.25      roma7     271:     my @sources;       
1.26      roma7     272:     open UNSORTED, ">unsorted";
1.5       boris     273:     while ($source = shift) {
1.25      roma7     274:        push @sources,glob($source);
                    275:     }
                    276:     foreach $source(@sources) {
1.17      boris     277:        my $TourNum=0;
1.5       boris     278:        my($PlayedAt) = '';
                    279:        my($QuestionId, $TourId, $TournamentId, $ParentId) = (0, 0, 0, 0);
1.14      boris     280:        my($tournum, $qnum, $all_qnum) = (0, 0, 0);
1.5       boris     281:        my (@d) = (localtime((stat($source))[9]))[5,4,3];
                    282:        $d[1]++;
                    283:        $d[0]+=1900;
                    284:        my ($CreatedAt) = $dbh->quote( join('-', @d));
1.6       boris     285: 
1.5       boris     286:        open INFD, $source 
                    287:            or die "Can't open input file: $!\n";
                    288:        
                    289:        $source =~ s/^.*\/([^\/]*)$/$1/;
                    290:        $source = $dbh->quote($source);
1.6       boris     291:        print STDERR "Файл: $source, дата: $CreatedAt ";
1.13      boris     292:        my %TourDefaults=('CreatedAt'=>$CreatedAt);
                    293:        my %QuestionDefaults=();
1.14      boris     294:        my %QuestionGlobalDefaults=('Type'=>$dbh->quote('Ч'));
1.5       boris     295:        while (($key, $value) = getField(\*INFD, $dbh)) {
                    296:            last if (!$key);
                    297:            
                    298:            if ($key =~ /Мета/) {
1.7       boris     299:                next;   # This is obsolete
1.5       boris     300:            }
1.10      boris     301:            if ($key =~ /Чемпионат/ || $key =~ /Пакет/) {               
1.7       boris     302:                ($TournamentId, $ParentId) = CheckFile($dbh,$source,$value);
                    303:                if (!$TournamentId)  {
                    304:                    last;
1.10      boris     305:                }       
1.7       boris     306:                $sth = $dbh->prepare("UPDATE Tournaments SET
1.10      boris     307:                                     Title=$value, Type='Ч', 
1.7       boris     308:                                      ParentId=$ParentId, 
                    309:                                      FileName=$source, 
                    310:                                      CreatedAt=$CreatedAt
                    311:                                      WHERE
                    312:                                      Id=$TournamentId");
1.5       boris     313:                $sth->execute;
                    314:                next;
                    315:            }
                    316:            if ($key =~ /Тур/) {
                    317:                if ($TourId) {
                    318:                    $dbh->do("UPDATE Tournaments SET QuestionsNum=$qnum
                    319:                              WHERE Id=$TourId");
                    320:                }
                    321:                $qnum = 0;
1.17      boris     322:                $TourNum++;
                    323:                $TourId=CreateTour($dbh,$value,$TournamentId,$TourNum,
                    324:                                   \%TourDefaults);
1.13      boris     325:                %QuestionDefaults=%QuestionGlobalDefaults;
                    326:                $QuestionId=0;
                    327:                next;   
1.5       boris     328:            }
                    329:            if ($key =~ /Вопрос/) {
1.11      boris     330:                if (!$TourId) {
                    331:                    $qnum = 0;
1.19      boris     332:                    $TourNum++;
                    333:                    $TourId=CreateTour($dbh,'1',$TournamentId,$TourNum,
1.13      boris     334:                                       \%TourDefaults);
                    335:                    %QuestionDefaults=%QuestionGlobalDefaults;
1.11      boris     336:                }
1.5       boris     337:                my $query = "INSERT INTO Questions 
1.14      boris     338:                             (ParentId, Number) 
                    339:                             VALUES ($TourId, $qnum+1)";
1.5       boris     340:                $sth = $dbh->prepare($query);
                    341:                $sth->execute or print $query;;
                    342:                $QuestionId = $sth->{mysql_insertid};
                    343:                &UpdateQuestion($dbh, $QuestionId, "Question", $value);
1.13      boris     344:                while (my ($key,$value)=each %QuestionDefaults) {
                    345:                    &UpdateQuestion($dbh, $QuestionId, $key, $value);
                    346:                }               
1.5       boris     347:                $qnum++;
                    348:                $all_qnum++;
                    349:                next;
                    350:            }
1.6       boris     351: 
                    352:            if ($key =~ /Ответ/) {
                    353:                &UpdateQuestion($dbh, $QuestionId, "Answer", $value);
                    354:                next;
                    355:            }
1.7       boris     356: 
1.6       boris     357:            if ($key =~ /Комментари/) {
                    358:                &UpdateQuestion($dbh, $QuestionId, "Comments", $value);
                    359:                next;
                    360:            }
1.5       boris     361:            
1.15      boris     362:            my @Fields = grep { $key =~ /$_/ } keys %QuestionFields;
1.6       boris     363: 
1.13      boris     364:            if (scalar @Fields) {
                    365:                my $word = shift @Fields;
                    366:                my $field = $QuestionFields{$word};
                    367:                if ($QuestionId) {
                    368:                    &UpdateQuestion($dbh, $QuestionId, $field, $value);
                    369:                } elsif ($TourId) {
                    370:                    $QuestionDefaults{$field}=$value;
                    371:                } else {
                    372:                    $QuestionGlobalDefaults{$field}=$value;
                    373:                }
1.6       boris     374:                next;
                    375:            }
                    376: 
1.15      boris     377:            @Fields = grep { $key =~ /$_/ } keys %TourFields;
1.6       boris     378: 
1.13      boris     379:            if (scalar @Fields) {
                    380:                my $word = shift @Fields;
                    381:                my $field = $TourFields{$word};
                    382:                if ($QuestionId) {
                    383:                    print STDERR "ОШИБКА: $key $value недопустимы после",
                    384:                    " начала вопросов\n";
                    385:                } elsif ($TourId) {
                    386:                    &UpdateTournament($dbh, $TourId, $field, $value);
1.5       boris     387:                } else {
1.13      boris     388:                    &UpdateTournament($dbh, $TournamentId, $field, $value);
                    389:                    $TourDefaults{$field}=$value;
1.1       boris     390:                }
1.6       boris     391:                next;
1.5       boris     392:            }
1.13      boris     393: 
1.6       boris     394:            
                    395:            #
                    396:            # If we are here, something got wrong!
                    397:            #
                    398:            print STDERR "\nЯ НЕ ПОНИМАЮ: $key, $value!\n";
                    399:            
1.5       boris     400:        }
                    401:        $dbh->do("UPDATE Tournaments SET QuestionsNum=$qnum
1.1       boris     402:                        WHERE Id=$TourId");
1.5       boris     403:        $dbh->do("UPDATE Tournaments SET QuestionsNum=$all_qnum
1.1       boris     404:                        WHERE Id=$TournamentId");
1.5       boris     405:        &UpdateParents($dbh, $ParentId, $all_qnum);             
1.6       boris     406:        print STDERR "Всего вопросов: $all_qnum \n";
1.5       boris     407:     }
1.27      roma7     408:     close UNSORTED;
                    409:     unlink "unsorted" unless $isunsorted;
1.5       boris     410:     $dbh->disconnect;
1.1       boris     411: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>