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