3 * ARC2 RDF Store LOAD Query Handler
5 * @author Benjamin Nowack
6 * @license <http://arc.semsol.org/license>
7 * @homepage <http://arc.semsol.org/>
12 ARC2::inc('StoreQueryHandler');
14 class ARC2_StoreLoadQueryHandler extends ARC2_StoreQueryHandler {
16 function __construct($a = '', &$caller) {/* caller has to be a store */
17 parent::__construct($a, $caller);
20 function ARC2_StoreLoadQueryHandler($a = '', &$caller) {
21 $this->__construct($a, $caller);
24 function __init() {/* db_con, store_log_inserts */
26 $this->store =& $this->caller;
27 $this->write_buffer_size = $this->v('store_write_buffer', 2500, $this->a);
28 $this->split_threshold = $this->v('store_split_threshold', 0, $this->a);
29 $this->has_pcre_unicode = @preg_match('/\pL/u', 'test');
30 $this->strip_mb_comp_str = $this->v('store_strip_mb_comp_str', 0, $this->a);
35 function runQuery($infos, $data = '', $keep_bnode_ids = 0) {
36 $url = $infos['query']['url'];
37 $graph = $infos['query']['target_graph'];
38 $this->target_graph = $graph ? $this->calcURI($graph) : $this->calcURI($url);
39 $this->fixed_target_graph = $graph ? $this->target_graph : '';
40 $this->keep_bnode_ids = $keep_bnode_ids;
43 $reader =& new ARC2_Reader($this->a, $this);
44 $reader->activate($url, $data);
45 /* format detection */
48 'sparqlxml' => 'SPOG',
50 'ntriples' => 'Turtle',
55 'sgajson' => 'SGAJSON',
58 $format = $reader->getFormat();
59 if (!$format || !isset($mappings[$format])) {
60 return $this->addError('No loader available for "' .$url. '": ' . $format);
63 $suffix = 'Store' . $mappings[$format] . 'Loader';
65 $cls = 'ARC2_' . $suffix;
66 $loader =& new $cls($this->a, $this);
67 $loader->setReader($reader);
69 if (!$this->store->getLock()) {
70 $l_name = $this->a['db_name'] . '.' . $this->store->getTablePrefix() . '.write_lock';
71 return $this->addError('Could not get lock in "runQuery" (' . $l_name . ')');
76 $this->t_start = ARC2::mtime();
77 $this->log_inserts = $this->v('store_log_inserts', 0, $this->a);
78 if ($this->log_inserts) {
79 @unlink("arc_insert_log.txt");
80 $this->inserts = array();
81 $this->insert_times = array();
82 $this->t_prev = $this->t_start;
83 $this->t_count_prev = 0 ;
86 $this->max_term_id = $this->getMaxTermID();
87 $this->max_triple_id = $this->getMaxTripleID();
88 $this->column_type = $this->store->getColumnType();
89 //$this->createMergeTable();
90 $this->term_ids = array();
91 $this->triple_ids = array();
92 $this->sql_buffers = array();
93 $r = $loader->parse($url, $data);
95 $this->checkSQLBuffers(1);
96 if ($this->log_inserts) {
99 $this->store->releaseLock();
100 //$this->dropMergeTable();
101 if ((rand(1, 100) == 1)) $this->store->optimizeTables();
103 $dur = round($t2 - $this->t_start, 4);
105 't_count' => $this->t_count,
108 if ($this->log_inserts) {
109 $r['inserts'] = $this->inserts;
110 $r['insert_times'] = $this->insert_times;
117 function addT($s, $p, $o, $s_type, $o_type, $o_dt = '', $o_lang = '') {
118 if (!$this->has_lock) return 0;
119 $type_ids = array ('uri' => '0', 'bnode' => '1' , 'literal' => '2');
120 $g = $this->getTermID($this->target_graph, '0', 'id');
121 $s = (($s_type == 'bnode') && !$this->keep_bnode_ids) ? '_:b' . abs(crc32($g . $s)) . '_' . (strlen($s) > 12 ? substr(substr($s, 2) , -10) : substr($s, 2)) : $s;
122 $o = (($o_type == 'bnode') && !$this->keep_bnode_ids) ? '_:b' . abs(crc32($g . $o)) . '_' . (strlen($o) > 12 ? substr(substr($o, 2), -10) : substr($o, 2)) : $o;
125 's' => $this->getTermID($s, $type_ids[$s_type], 's'),
126 'p' => $this->getTermID($p, '0', 'id'),
127 'o' => $this->getTermID($o, $type_ids[$o_type], 'o'),
128 'o_lang_dt' => $this->getTermID($o_dt . $o_lang, $o_dt ? '0' : '2', 'id'),
129 'o_comp' => $this->getOComp($o),
130 's_type' => $type_ids[$s_type],
131 'o_type' => $type_ids[$o_type],
133 $t['t'] = $this->getTripleID($t);
134 if (is_array($t['t'])) {/* t exists already */
135 $t['t'] = $t['t'][0];
138 $this->bufferTripleSQL($t);
141 $g2t = array('g' => $g, 't' => $t['t']);
142 $this->bufferGraphSQL($g2t);
145 if (($this->t_count % $this->write_buffer_size) == 0) {
147 $reset_buffers = (($this->t_count % ($this->write_buffer_size * 2)) == 0);
148 $refresh_lock = (($this->t_count % 25000) == 0);
149 $split_tables = (($this->t_count % ($this->write_buffer_size * 10)) == 0);
150 if ($this->log_inserts) $this->logInserts();
151 $this->checkSQLBuffers($force_write, $reset_buffers, $refresh_lock, $split_tables);
157 function getMaxTermID() {
158 $con = $this->store->getDBCon();
160 foreach (array('id2val', 's2val', 'o2val') as $tbl) {
161 $sql .= $sql ? ' UNION ' : '';
162 $sql .= "(SELECT MAX(id) as `id` FROM " . $this->store->getTablePrefix() . $tbl . ')';
165 if (($rs = $this->queryDB($sql, $con)) && mysql_num_rows($rs)) {
166 while ($row = mysql_fetch_array($rs)) {
167 $r = ($r < $row['id']) ? $row['id'] : $r;
173 function getMaxTripleID() {
174 $con = $this->store->getDBCon();
175 $sql = "SELECT MAX(t) AS `id` FROM " . $this->store->getTablePrefix() . "triple";
176 if (($rs = $this->queryDB($sql, $con)) && mysql_num_rows($rs) && ($row = mysql_fetch_array($rs))) {
177 return $row['id'] + 1;
182 function getTermID($val, $type_id, $tbl) {
183 $con = $this->store->getDBCon();
185 if (isset($this->term_ids[$val])) {
186 if (!isset($this->term_ids[$val][$tbl])) {
187 foreach (array('id', 's', 'o') as $other_tbl) {
188 if (isset($this->term_ids[$val][$other_tbl])) {
189 $this->term_ids[$val][$tbl] = $this->term_ids[$val][$other_tbl];
190 $this->bufferIDSQL($tbl, $this->term_ids[$val][$tbl], $val, $type_id);
195 return $this->term_ids[$val][$tbl];
198 $tbl_prefix = $this->store->getTablePrefix();
199 $sub_tbls = ($tbl == 'id') ? array('id2val', 's2val', 'o2val') : ($tbl == 's' ? array('s2val', 'id2val', 'o2val') : array('o2val', 'id2val', 's2val'));
200 foreach ($sub_tbls as $sub_tbl) {
202 //$sql = "SELECT id AS `id`, '" . $sub_tbl . "' AS `tbl` FROM " . $tbl_prefix . $sub_tbl . " WHERE val = BINARY '" . mysql_real_escape_string($val, $con) . "'";
204 if (preg_match('/^(s2val|o2val)$/', $sub_tbl) && $this->hasHashColumn($sub_tbl)) {
205 $sql = "SELECT id AS `id`, val AS `val` FROM " . $tbl_prefix . $sub_tbl . " WHERE val_hash = BINARY '" . $this->getValueHash($val) . "'";
206 if (($rs = $this->queryDB($sql, $con)) && mysql_num_rows($rs)) {
207 while ($row = mysql_fetch_array($rs)) {
208 if ($row['val'] == $val) {
216 $sql = "SELECT id AS `id` FROM " . $tbl_prefix . $sub_tbl . " WHERE val = BINARY '" . mysql_real_escape_string($val, $con) . "'";
217 if (($rs = $this->queryDB($sql . ' LIMIT 1', $con)) && mysql_num_rows($rs)) {
218 $row = mysql_fetch_array($rs);
223 $this->term_ids[$val] = array($tbl => $id);
224 if ($sub_tbl != $tbl . '2val') {
225 $this->bufferIDSQL($tbl, $id, $val, $type_id);
231 if (!isset($this->term_ids[$val])) {
232 $this->term_ids[$val] = array($tbl => $this->max_term_id);
233 $this->bufferIDSQL($tbl, $this->max_term_id, $val, $type_id);
234 $this->max_term_id++;
235 /* upgrade tables ? */
236 if (($this->column_type == 'mediumint') && ($this->max_term_id >= 16750000)) {
237 $this->store->extendColumns();
238 $this->column_type = 'int';
241 return $this->term_ids[$val][$tbl];
244 function getTripleID($t) {
245 $con = $this->store->getDBCon();
246 $val = serialize($t);
248 if (isset($this->triple_ids[$val])) {
249 return array($this->triple_ids[$val]);/* hack for "don't insert this triple" */
252 $sql = "SELECT t FROM " . $this->store->getTablePrefix() . "triple WHERE
253 s = " . $t['s'] . " AND p = " . $t['p'] . " AND o = " . $t['o'] . " AND o_lang_dt = " . $t['o_lang_dt'] . " AND s_type = " . $t['s_type'] . " AND o_type = " . $t['o_type'] . "
256 if (($rs = $this->queryDB($sql, $con)) && mysql_num_rows($rs) && ($row = mysql_fetch_array($rs))) {
257 $this->triple_ids[$val] = $row['t'];/* hack for "don't insert this triple" */
258 return array($row['t']);/* hack for "don't insert this triple" */
262 $this->triple_ids[$val] = $this->max_triple_id;
263 $this->max_triple_id++;
265 if ($this->split_threshold && !($this->max_triple_id % $this->split_threshold)) {
266 $this->store->splitTables();
267 $this->dropMergeTable();
268 $this->createMergeTable();
270 return $this->triple_ids[$val];
274 function getOComp($val) {
275 /* try date (e.g. 21 August 2007) */
276 if (preg_match('/^[0-9]{1,2}\s+[a-z]+\s+[0-9]{4}/i', $val) && ($uts = strtotime($val)) && ($uts !== -1)) {
277 return date("Y-m-d\TH:i:s", $uts);
279 /* xsd date (e.g. 2009-05-28T18:03:38+09:00 2009-05-28T18:03:38GMT) */
280 if (preg_match('/^([0-9]{4}\-[0-9]{2}\-[0-9]{2}\T)([0-9\:]+)?([0-9\+\-\:\Z]+)?(\s*[a-z]{2,3})?$/si', $val, $m)) {
286 /* timezone offset */
287 if (isset($m[3]) && ($m[3] != 'Z')) {
288 $uts = strtotime(str_replace('T', ' ', $val));
289 if (preg_match('/([\+\-])([0-9]{2})\:?([0-9]{2})$/', $m[3], $sub_m)) {
290 $diff_mins = (3600 * ltrim($sub_m[2], '0')) + ltrim($sub_m[3], '0');
291 $uts = ($sub_m[1] == '-') ? $uts + $diff_mins : $uts - $diff_mins;
292 $val = date('Y-m-d\TH:i:s\Z', $uts);
301 /* fallback & backup w/o UTC calculation, to be removed in later revision */
302 if (preg_match('/^[0-9]{4}[0-9\-\:\T\Z\+]+([a-z]{2,3})?$/i', $val)) {
305 if (is_numeric($val)) {
306 $val = sprintf("%f", $val);
307 if (preg_match("/([\-\+])([0-9]*)\.([0-9]*)/", $val, $m)) {
308 return $m[1] . sprintf("%018s", $m[2]) . "." . sprintf("%-015s", $m[3]);
310 if (preg_match("/([0-9]*)\.([0-9]*)/", $val, $m)) {
311 return "+" . sprintf("%018s", $m[1]) . "." . sprintf("%-015s", $m[2]);
315 /* any other string: remove tags, linebreaks etc., but keep MB-chars */
316 //$val = substr(trim(preg_replace('/[\W\s]+/is', '-', strip_tags($val))), 0, 35);
317 $re = $this->has_pcre_unicode ? '/[\PL\s]+/isu' : '/[\s\'\"\ยด\`]+/is';
318 $val = trim(preg_replace($re, '-', strip_tags($val)));
319 if (strlen($val) > 35) {
320 $fnc = function_exists("mb_substr") ? 'mb_substr' : 'substr';
321 $val = $fnc($val, 0, 17) . '-' . $fnc($val, -17);
323 if ($this->strip_mb_comp_str) {
324 $val = urldecode(preg_replace('/\%[0-9A-F]{2}/', '', urlencode($val)));
326 return $this->toUTF8($val);
331 function bufferTripleSQL($t) {
332 $con = $this->store->getDBCon();
335 if (!isset($this->sql_buffers[$tbl])) {
336 $this->sql_buffers[$tbl] = "INSERT IGNORE INTO " . $this->store->getTablePrefix() . $tbl . " (t, s, p, o, o_lang_dt, o_comp, s_type, o_type) VALUES";
339 $this->sql_buffers[$tbl] .= $sql . "(" . $t['t'] . ", " . $t['s'] . ", " . $t['p'] . ", " . $t['o'] . ", " . $t['o_lang_dt'] . ", '" . mysql_real_escape_string($t['o_comp'], $con) . "', " . $t['s_type'] . ", " . $t['o_type'] . ")";
342 function bufferGraphSQL($g2t) {
345 if (!isset($this->sql_buffers[$tbl])) {
346 $this->sql_buffers[$tbl] = "INSERT IGNORE INTO " . $this->store->getTablePrefix() . $tbl . " (g, t) VALUES";
349 $this->sql_buffers[$tbl] .= $sql . "(" . $g2t['g'] . ", " . $g2t['t'] . ")";
352 function bufferIDSQL($tbl, $id, $val, $val_type) {
353 $con = $this->store->getDBCon();
354 $tbl = $tbl . '2val';
355 if ($tbl == 'id2val') {
356 $cols = "id, val, val_type";
357 $vals = "(" . $id . ", '" . mysql_real_escape_string($val, $con) . "', " . $val_type . ")";
359 elseif (preg_match('/^(s2val|o2val)$/', $tbl) && $this->hasHashColumn($tbl)) {
360 $cols = "id, val_hash, val";
361 $vals = "(" . $id . ", '" . $this->getValueHash($val). "', '" . mysql_real_escape_string($val, $con) . "')";
365 $vals = "(" . $id . ", '" . mysql_real_escape_string($val, $con) . "')";
367 if (!isset($this->sql_buffers[$tbl])) {
368 $this->sql_buffers[$tbl] = '';
369 $sql = "INSERT IGNORE INTO " . $this->store->getTablePrefix() . $tbl . "(" . $cols . ") VALUES ";
375 $this->sql_buffers[$tbl] .= $sql;
380 function checkSQLBuffers($force_write = 0, $reset_id_buffers = 0, $refresh_lock = 0, $split_tables = 0) {
381 $con = $this->store->getDBCon();
382 if (!$this->keep_time_limit) @set_time_limit($this->v('time_limit', 60, $this->a));
383 foreach (array('triple', 'g2t', 'id2val', 's2val', 'o2val') as $tbl) {
384 $buffer_size = isset($this->sql_buffers[$tbl]) ? 1 : 0;
385 if ($buffer_size && $force_write) {
387 $this->queryDB($this->sql_buffers[$tbl], $con);
389 if ($er = mysql_error($con)) {
390 $this->autoRepairTable($er, $con, $this->sql_buffers[$tbl]);
392 unset($this->sql_buffers[$tbl]);
393 if ($this->log_inserts) {
395 $this->inserts[$tbl] = $this->v($tbl, 0, $this->inserts) + max(0, mysql_affected_rows($con));
396 $dur = round($t2 - $t1, 4);
397 $this->insert_times[$tbl] = isset($this->insert_times[$tbl]) ? $this->insert_times[$tbl] : array('min' => $dur, 'max' => $dur, 'sum' => $dur);
398 $this->insert_times[$tbl] = array('min' => min($dur, $this->insert_times[$tbl]['min']), 'max' => max($dur, $this->insert_times[$tbl]['max']), 'sum' => $dur + $this->insert_times[$tbl]['sum']);
400 /* reset term id buffers */
401 if ($reset_id_buffers) {
402 $this->term_ids = array();
403 $this->triple_ids = array();
407 $this->store->releaseLock();
410 if (!$this->store->getLock(5)) return $this->addError('Could not re-obtain lock in "checkSQLBuffers"');
418 function autoRepairTable($er, $con, $sql = '') {
419 $this->addError('MySQL error: ' . $er . ' (' . $sql . ')');
420 if (preg_match('/Table \'[^\']+\/([a-z0-9\_\-]+)\' .*(crashed|repair)/i', $er, $m)) {
421 $rs = $this->queryDB('REPAIR TABLE ' . rawurlencode($m[1]), $con);
422 $msg = $rs ? mysql_fetch_array($rs) : array();
423 if ($this->v('Msg_type', 'error', $msg) == 'error') {
425 if ($this->v('store_reset_on_table_crash', 0, $this->a)) {
426 $this->store->drop();
427 $this->store->setUp();
430 $er = $this->v('Msg_text', 'unknown error', $msg);
431 $this->addError('Auto-repair failed on ' . rawurlencode($m[1]) . ': ' . $er);
433 //die("Fatal errors: \n" . print_r($this->getErrors(), 1));
440 function logInserts() {
441 $t_start = $this->t_start;
442 $t_prev = $this->t_prev;
443 $t_now = ARC2::mtime();
444 $tc_prev = $this->t_count_prev;
445 $tc_now = $this->t_count;
446 $tc_diff = $tc_now - $tc_prev;
448 $dur_full = $t_now - $t_start;
449 $dur_diff = $t_now - $t_prev;
451 $speed_full = round($tc_now / $dur_full);
452 $speed_now = round($tc_diff / $dur_diff);
454 $r = $tc_diff . ' in ' . round($dur_diff, 5) . ' = ' . $speed_now . ' t/s (' .$tc_now. ' in ' . round($dur_full, 5). ' = ' . $speed_full . ' t/s )';
455 $fp = @fopen("arc_insert_log.txt", "a");
456 @fwrite($fp, $r . "\r\n");
459 $this->t_prev = $t_now;
460 $this->t_count_prev = $tc_now;