-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimportPGN.php
More file actions
98 lines (82 loc) · 2.73 KB
/
Copy pathimportPGN.php
File metadata and controls
98 lines (82 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
include('class/State.php');
include('class/Match.php');
include('class/Piece.php');
include('class/Board.php');
include('class/PGN.php');
// Command line
$argv = $GLOBALS['argv'];
if(!isset($argv[1]) || empty($argv[1]) || !file_exists($argv[1])) {
echo "Use: importPGN <File.pgn> [IMP to import] [# macth to debug]\n\n";
exit(1);
}
// To import the PGN to the database use "IMP" as 1st command line arg
$doImport = (isset($argv[2]) && $argv[2]=='IMP');
// Use # of match to debug, or "DB" to debug queries
$debug = !isset($argv[3]) ? 0 : ($argv[3]=='DB' ? true : (int)$argv[3]);
if($doImport) {
$conn = pg_connect("host=vm dbname=chess user=sa_chess password=1234");
if(!$conn) {
echo "Error connecting to BD\n\n";
exit(2);
}
if(Match::checkDB($conn)) {
echo "Created tables [match] and [boardstate].\n";
}
}
// Load PGN
$pgn = new PGN($argv[1]);
// Parse PGN
$matches = $pgn->loadMatches();
echo ($doImport ? "Importing " : 'Checking ').count($matches)." matches\n\n";
// Importing
$numMatch = 0;
$numError = 0;
while(($match = array_shift($matches))) {
$numMatch++;
try {
$match->play(($debug === true || $numMatch == $debug));
} catch(Exception $e) {
$numError++;
echo "-- !!! Skiping Match $numMatch :: ".$e->getMessage()." :: !!!\n";
if($numMatch == $debug) die();
continue;
}
if($doImport) {
// Check if is duplicate
if($match->existsOnDB($conn)) {
echo "!!! Skiping Match $numMatch :: Already one like this on DB :: !!!\n";
continue;
}
echo "> Importing Match $numMatch :: ".$match->getTotalMoves()." moves: ";
pg_query($conn, 'BEGIN');
$sqlMatch = $match->getInsertSQL();
if($debug === true) echo "SQLmatch: $sqlMatch\n";
$res = pg_query($conn, $sqlMatch . ' RETURNING id');
if(!$res) {
echo "!!! Skiping Match $numMatch :: DB failure :: !!!\n";
echo "Match:\n$match\n";
pg_query($conn, 'ROLLBACK');
continue;
}
$idMatchBD = pg_fetch_array($res)[0];
foreach($match->getStates() as $state) {
$sqlState = $state->getInsertSQL($idMatchBD);
if($debug === true) echo "SQLstate: $sqlState\n";
$res = pg_query($conn, $sqlState);
if(!$res) {
echo "!!! Skiping Match $numMatch :: DB failure 2 :: !!!\n";
pg_query($conn, 'ROLLBACK');
continue 2;
}
}
echo "OK!\n";
pg_query($conn, 'COMMIT');
}
}
if($numError) {
echo "\nFound $numError macthes with errors!\n\n";
} else {
echo "\nAll matches OK!\n\n";
}
exit(0);