PageRenderTime 49ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/arc/store/ARC2_StoreSelectQueryHandler.php

http://puelia-php.googlecode.com/
PHP | 1786 lines | 1536 code | 124 blank | 126 comment | 395 complexity | ef6b3e0929fdbee096c989ec9890e8f3 MD5 | raw file
Possible License(s): Apache-2.0, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * ARC2 RDF Store SELECT Query Handler
  4. *
  5. * @author Benjamin Nowack
  6. * @license http://arc.semsol.org/license
  7. * @homepage <http://arc.semsol.org/>
  8. * @package ARC2
  9. * @version 2010-11-16
  10. *
  11. */
  12. ARC2::inc('StoreQueryHandler');
  13. class ARC2_StoreSelectQueryHandler extends ARC2_StoreQueryHandler {
  14. function __construct($a, &$caller) {/* caller has to be a store */
  15. parent::__construct($a, $caller);
  16. }
  17. function __init() {/* db_con */
  18. parent::__init();
  19. $this->store = $this->caller;
  20. $con = $this->store->getDBCon();
  21. $this->handler_type = 'select';
  22. $this->engine_type = $this->v('store_engine_type', 'MyISAM', $this->a);
  23. $this->cache_results = $this->v('store_cache_results', 0, $this->a);
  24. }
  25. /* */
  26. function runQuery($infos) {
  27. $con = $this->store->getDBCon();
  28. $rf = $this->v('result_format', '', $infos);
  29. $this->infos = $infos;
  30. $this->infos['null_vars'] = array();
  31. $this->indexes = array();
  32. $this->pattern_order_offset = 0;
  33. $q_sql = $this->getSQL();
  34. /* debug result formats */
  35. if ($rf == 'sql') return $q_sql;
  36. if ($rf == 'structure') return $this->infos;
  37. if ($rf == 'index') return $this->indexes;
  38. /* create intermediate results (ID-based) */
  39. $tmp_tbl = $this->createTempTable($q_sql);
  40. /* join values */
  41. $r = $this->getFinalQueryResult($q_sql, $tmp_tbl);
  42. /* remove intermediate results */
  43. if (!$this->cache_results) {
  44. $this->queryDB('DROP TABLE IF EXISTS ' . $tmp_tbl, $con);
  45. }
  46. return $r;
  47. }
  48. function getSQL() {
  49. $r = '';
  50. $nl = "\n";
  51. $this->buildInitialIndexes();
  52. foreach ($this->indexes as $i => $index) {
  53. $this->index = array_merge($this->getEmptyIndex(), $index);
  54. $this->analyzeIndex($this->getPattern('0'));
  55. $sub_r = $this->getQuerySQL();
  56. $r .= $r ? $nl . 'UNION' . $this->getDistinctSQL() . $nl : '';
  57. $r .= $this->is_union_query ? '(' . $sub_r . ')' : $sub_r;
  58. $this->indexes[$i] = $this->index;
  59. }
  60. $r .= $this->is_union_query ? $this->getLIMITSQL() : '';
  61. if ($this->v('order_infos', 0, $this->infos['query'])) {
  62. $r = preg_replace('/SELECT(\s+DISTINCT)?\s*/', 'SELECT\\1 NULL AS `_pos_`, ', $r);
  63. }
  64. if ($pd_count = $this->problematicDependencies()) {
  65. /* re-arranging the patterns sometimes reduces the LEFT JOIN dependencies */
  66. $set_sql = 0;
  67. if (!$this->pattern_order_offset) $set_sql = 1;
  68. if (!$set_sql && ($pd_count < $this->opt_sql_pd_count)) $set_sql = 1;
  69. if (!$set_sql && ($pd_count == $this->opt_sql_pd_count) && (strlen($r) < strlen($this->opt_sql))) $set_sql = 1;
  70. if ($set_sql) {
  71. $this->opt_sql = $r;
  72. $this->opt_sql_pd_count = $pd_count;
  73. }
  74. $this->pattern_order_offset++;
  75. if ($this->pattern_order_offset > 5) {
  76. return $this->opt_sql;
  77. }
  78. return $this->getSQL();
  79. }
  80. return $r;
  81. }
  82. function buildInitialIndexes() {
  83. $this->dependency_log = array();
  84. $this->index = $this->getEmptyIndex();
  85. $this->buildIndex($this->infos['query']['pattern'], 0);
  86. $tmp = $this->index;
  87. $this->analyzeIndex($this->getPattern('0'));
  88. $this->initial_index = $this->index;
  89. $this->index = $tmp;
  90. $this->is_union_query = $this->index['union_branches'] ? 1 : 0;
  91. $this->indexes = $this->is_union_query ? $this->getUnionIndexes($this->index) : array($this->index);
  92. }
  93. function createTempTable($q_sql) {
  94. $con = $this->store->getDBCon();
  95. $v = $this->store->getDBVersion();
  96. if ($this->cache_results) {
  97. $tbl = $this->store->getTablePrefix() . 'Q' . md5($q_sql);
  98. }
  99. else {
  100. $tbl = $this->store->getTablePrefix() . 'Q' . md5($q_sql . time() . uniqid(rand()));
  101. }
  102. if (strlen($tbl) > 64) $tbl = 'Q' . md5($tbl);
  103. $tmp_sql = 'CREATE TEMPORARY TABLE ' . $tbl . ' ( ' . $this->getTempTableDef($tbl, $q_sql) . ') ';
  104. $tmp_sql .= (($v < '04-01-00') && ($v >= '04-00-18')) ? 'ENGINE' : (($v >= '04-01-02') ? 'ENGINE' : 'TYPE');
  105. $tmp_sql .= '=' . $this->engine_type;/* HEAP doesn't support AUTO_INCREMENT, and MySQL breaks on MEMORY sometimes */
  106. if (!$this->queryDB($tmp_sql, $con) && !$this->queryDB(str_replace('CREATE TEMPORARY', 'CREATE', $tmp_sql), $con)) {
  107. return $this->addError(mysql_error($con));
  108. }
  109. mysql_unbuffered_query('INSERT INTO ' . $tbl . ' ' . "\n" . $q_sql, $con);
  110. if ($er = mysql_error($con)) $this->addError($er);
  111. return $tbl;
  112. }
  113. function getEmptyIndex() {
  114. return array(
  115. 'from' => array(),
  116. 'join' => array(),
  117. 'left_join' => array(),
  118. 'vars' => array(), 'graph_vars' => array(), 'graph_uris' => array(),
  119. 'bnodes' => array(),
  120. 'triple_patterns' => array(),
  121. 'sub_joins' => array(),
  122. 'constraints' => array(),
  123. 'union_branches'=> array(),
  124. 'patterns' => array(),
  125. 'havings' => array()
  126. );
  127. }
  128. function getTempTableDef($tmp_tbl, $q_sql) {
  129. $col_part = preg_replace('/^SELECT\s*(DISTINCT)?(.*)FROM.*$/s', '\\2', $q_sql);
  130. $parts = explode(',', $col_part);
  131. $has_order_infos = $this->v('order_infos', 0, $this->infos['query']);
  132. $r = '';
  133. $added = array();
  134. foreach ($parts as $part) {
  135. if (preg_match('/\.?(.+)\s+AS\s+`(.+)`/U', trim($part), $m) && !isset($added[$m[2]])) {
  136. $col = $m[1];
  137. $alias = $m[2];
  138. if ($alias == '_pos_') continue;
  139. $r .= $r ? ',' : '';
  140. $r .= "\n `" . $alias . "` int UNSIGNED";
  141. $added[$alias] = 1;
  142. }
  143. }
  144. if ($has_order_infos) {
  145. $r = "\n" . '`_pos_` mediumint NOT NULL AUTO_INCREMENT PRIMARY KEY, ' . $r;
  146. }
  147. return $r ? $r . "\n" : '';
  148. }
  149. function getFinalQueryResult($q_sql, $tmp_tbl) {
  150. /* var names */
  151. $vars = array();
  152. $aggregate_vars = array();
  153. foreach ($this->infos['query']['result_vars'] as $entry) {
  154. if ($entry['aggregate']) {
  155. $vars[] = $entry['alias'];
  156. $aggregate_vars[] = $entry['alias'];
  157. }
  158. else {
  159. $vars[] = $entry['var'];
  160. }
  161. }
  162. /* result */
  163. $r = array('variables' => $vars);
  164. $v_sql = $this->getValueSQL($tmp_tbl, $q_sql);
  165. //echo "\n\n" . $v_sql;
  166. $t1 = ARC2::mtime();
  167. $con = $this->store->getDBCon();
  168. $rs = mysql_unbuffered_query($v_sql, $con);
  169. if ($er = mysql_error($con)) {
  170. $this->addError($er);
  171. }
  172. $t2 = ARC2::mtime();
  173. $rows = array();
  174. $types = array(0 => 'uri', 1 => 'bnode', 2 => 'literal');
  175. if ($rs) {
  176. while ($pre_row = mysql_fetch_array($rs)) {
  177. $row = array();
  178. foreach ($vars as $var) {
  179. if (isset($pre_row[$var])) {
  180. $row[$var] = $pre_row[$var];
  181. $row[$var . ' type'] = isset($pre_row[$var . ' type']) ? $types[$pre_row[$var . ' type']] : (in_array($var, $aggregate_vars) ? 'literal' : 'uri');
  182. if (isset($pre_row[$var . ' lang_dt']) && ($lang_dt = $pre_row[$var . ' lang_dt'])) {
  183. if (preg_match('/^([a-z]+(\-[a-z0-9]+)*)$/i', $lang_dt)) {
  184. $row[$var . ' lang'] = $lang_dt;
  185. }
  186. else {
  187. $row[$var . ' datatype'] = $lang_dt;
  188. }
  189. }
  190. }
  191. }
  192. if ($row || !$vars) {
  193. $rows[] = $row;
  194. }
  195. }
  196. }
  197. $r['rows'] = $rows;
  198. return $r;
  199. }
  200. /* */
  201. function buildIndex($pattern, $id) {
  202. $pattern['id'] = $id;
  203. $type = $this->v('type', '', $pattern);
  204. if (($type == 'filter') && $this->v('constraint', 0, $pattern)) {
  205. $sub_pattern = $pattern['constraint'];
  206. $sub_pattern['parent_id'] = $id;
  207. $sub_id = $id . '_0';
  208. $this->buildIndex($sub_pattern, $sub_id);
  209. $pattern['constraint'] = $sub_id;
  210. }
  211. else {
  212. $sub_patterns = $this->v('patterns', array(), $pattern);
  213. $keys = array_keys($sub_patterns);
  214. $spc = count($sub_patterns);
  215. if (($spc > 4) && $this->pattern_order_offset) {
  216. $keys = array();
  217. for ($i = 0 ; $i < $spc; $i++) {
  218. $keys[$i] = $i + $this->pattern_order_offset;
  219. while ($keys[$i] >= $spc) $keys[$i] -= $spc;
  220. }
  221. }
  222. foreach ($keys as $i => $key) {
  223. $sub_pattern = $sub_patterns[$key];
  224. $sub_pattern['parent_id'] = $id;
  225. $sub_id = $id . '_' . $key;
  226. $this->buildIndex($sub_pattern, $sub_id);
  227. $pattern['patterns'][$i] = $sub_id;
  228. if ($type == 'union') {
  229. $this->index['union_branches'][] = $sub_id;
  230. }
  231. }
  232. }
  233. $this->index['patterns'][$id] = $pattern;
  234. }
  235. /* */
  236. function analyzeIndex($pattern) {
  237. $type = $pattern['type'];
  238. $id = $pattern['id'];
  239. /* triple */
  240. if ($type == 'triple') {
  241. foreach (array('s', 'p', 'o') as $term) {
  242. if ($pattern[$term . '_type'] == 'var') {
  243. $val = $pattern[$term];
  244. $this->index['vars'][$val] = array_merge($this->v($val, array(), $this->index['vars']), array(array('table' => $pattern['id'], 'col' =>$term)));
  245. }
  246. if ($pattern[$term . '_type'] == 'bnode') {
  247. $val = $pattern[$term];
  248. $this->index['bnodes'][$val] = array_merge($this->v($val, array(), $this->index['bnodes']), array(array('table' => $pattern['id'], 'col' =>$term)));
  249. }
  250. }
  251. $this->index['triple_patterns'][] = $pattern['id'];
  252. /* joins */
  253. if ($this->isOptionalPattern($id)) {
  254. $this->index['left_join'][] = $id;
  255. }
  256. elseif (!$this->index['from']) {
  257. $this->index['from'][] = $id;
  258. }
  259. elseif (!$this->getJoinInfos($id)) {
  260. $this->index['from'][] = $id;
  261. }
  262. else {
  263. $this->index['join'][] = $id;
  264. }
  265. /* graph infos, graph vars */
  266. $this->index['patterns'][$id]['graph_infos'] = $this->getGraphInfos($id);
  267. foreach ($this->index['patterns'][$id]['graph_infos'] as $info) {
  268. if ($info['type'] == 'graph') {
  269. if ($info['var']) {
  270. $val = $info['var']['value'];
  271. $this->index['graph_vars'][$val] = array_merge($this->v($val, array(), $this->index['graph_vars']), array(array('table' => $id)));
  272. }
  273. elseif ($info['uri']) {
  274. $val = $info['uri'];
  275. $this->index['graph_uris'][$val] = array_merge($this->v($val, array(), $this->index['graph_uris']), array(array('table' => $id)));
  276. }
  277. }
  278. }
  279. }
  280. $sub_ids = $this->v('patterns', array(), $pattern);
  281. foreach ($sub_ids as $sub_id) {
  282. $this->analyzeIndex($this->getPattern($sub_id));
  283. }
  284. }
  285. /* */
  286. function getGraphInfos($id) {
  287. $r = array();
  288. if ($id) {
  289. $pattern = $this->index['patterns'][$id];
  290. $type = $pattern['type'];
  291. /* graph */
  292. if ($type == 'graph') {
  293. $r[] = array('type' => 'graph', 'var' => $pattern['var'], 'uri' => $pattern['uri']);
  294. }
  295. $p_pattern = $this->index['patterns'][$pattern['parent_id']];
  296. if (isset($p_pattern['graph_infos'])) {
  297. return array_merge($p_pattern['graph_infos'], $r);
  298. }
  299. return array_merge($this->getGraphInfos($pattern['parent_id']), $r);
  300. }
  301. /* FROM / FROM NAMED */
  302. else {
  303. if (isset($this->infos['query']['dataset'])) {
  304. foreach ($this->infos['query']['dataset'] as $set) {
  305. $r[] = array_merge(array('type' => 'dataset'), $set);
  306. }
  307. }
  308. }
  309. return $r;
  310. }
  311. /* */
  312. function getPattern($id) {
  313. if (is_array($id)) {
  314. return $id;
  315. }
  316. return $this->v($id, array(), $this->index['patterns']);
  317. }
  318. function getInitialPattern($id) {
  319. return $this->v($id, array(), $this->initial_index['patterns']);
  320. }
  321. /* */
  322. function getUnionIndexes($pre_index) {
  323. $r = array();
  324. $branches = array();
  325. $min_depth = 1000;
  326. /* only process branches with minimum depth */
  327. foreach ($pre_index['union_branches'] as $id) {
  328. $branches[$id] = count(preg_split('/\_/', $id));
  329. $min_depth = min($min_depth, $branches[$id]);
  330. }
  331. foreach ($branches as $branch_id => $depth) {
  332. if ($depth == $min_depth) {
  333. $union_id = preg_replace('/\_[0-9]+$/', '', $branch_id);
  334. $index = array('keeping' => $branch_id, 'union_branches' => array(), 'patterns' => $pre_index['patterns']);
  335. $old_branches = $index['patterns'][$union_id]['patterns'];
  336. $skip_id = ($old_branches[0] == $branch_id) ? $old_branches[1] : $old_branches[0];
  337. $index['patterns'][$union_id]['type'] = 'group';
  338. $index['patterns'][$union_id]['patterns'] = array($branch_id);
  339. $has_sub_unions = 0;
  340. foreach ($index['patterns'] as $pattern_id => $pattern) {
  341. if (preg_match('/^' .$skip_id. '/', $pattern_id)) {
  342. unset($index['patterns'][$pattern_id]);
  343. }
  344. elseif ($pattern['type'] == 'union') {
  345. foreach ($pattern['patterns'] as $sub_union_branch_id) {
  346. $index['union_branches'][] = $sub_union_branch_id;
  347. }
  348. }
  349. }
  350. if ($index['union_branches']) {
  351. $r = array_merge($r, $this->getUnionIndexes($index));
  352. }
  353. else {
  354. $r[] = $index;
  355. }
  356. }
  357. }
  358. return $r;
  359. }
  360. /* */
  361. function isOptionalPattern($id) {
  362. $pattern = $this->getPattern($id);
  363. if ($this->v('type', '', $pattern) == 'optional') {
  364. return 1;
  365. }
  366. if ($this->v('parent_id', '0', $pattern) == '0') {
  367. return 0;
  368. }
  369. return $this->isOptionalPattern($pattern['parent_id']);
  370. }
  371. function getOptionalPattern($id) {
  372. $pn = $this->getPattern($id);
  373. do {
  374. $pn = $this->getPattern($pn['parent_id']);
  375. } while ($pn['parent_id'] && ($pn['type'] != 'optional'));
  376. return $pn['id'];
  377. }
  378. function sameOptional($id, $id2) {
  379. return $this->getOptionalPattern($id) == $this->getOptionalPattern($id2);
  380. }
  381. /* */
  382. function isUnionPattern($id) {
  383. $pattern = $this->getPattern($id);
  384. if ($this->v('type', '', $pattern) == 'union') {
  385. return 1;
  386. }
  387. if ($this->v('parent_id', '0', $pattern) == '0') {
  388. return 0;
  389. }
  390. return $this->isUnionPattern($pattern['parent_id']);
  391. }
  392. /* */
  393. function getValueTable($col) {
  394. return $this->store->getTablePrefix() . (preg_match('/^(s|o)$/', $col) ? $col . '2val' : 'id2val');
  395. }
  396. function getGraphTable() {
  397. return $this->store->getTablePrefix() . 'g2t';
  398. }
  399. /* */
  400. function getQuerySQL() {
  401. $nl = "\n";
  402. $where_sql = $this->getWHERESQL(); /* pre-fills $index['sub_joins'] $index['constraints'] */
  403. $order_sql = $this->getORDERSQL(); /* pre-fills $index['sub_joins'] $index['constraints'] */
  404. return '' .
  405. ($this->is_union_query ? 'SELECT' : 'SELECT' . $this->getDistinctSQL()) . $nl .
  406. $this->getResultVarsSQL() . $nl . /* fills $index['sub_joins'] */
  407. $this->getFROMSQL() .
  408. $this->getAllJoinsSQL() .
  409. $this->getWHERESQL() .
  410. $this->getGROUPSQL() .
  411. $this->getORDERSQL() .
  412. ($this->is_union_query ? '' : $this->getLIMITSQL()) .
  413. $nl .
  414. '';
  415. }
  416. /* */
  417. function getDistinctSQL() {
  418. if ($this->is_union_query) {
  419. return ($this->v('distinct', 0, $this->infos['query']) || $this->v('reduced', 0, $this->infos['query'])) ? '' : ' ALL';
  420. }
  421. return ($this->v('distinct', 0, $this->infos['query']) || $this->v('reduced', 0, $this->infos['query'])) ? ' DISTINCT' : '';
  422. }
  423. /* */
  424. function getResultVarsSQL() {
  425. $r = '';
  426. $vars = $this->infos['query']['result_vars'];
  427. $nl = "\n";
  428. $added = array();
  429. foreach ($vars as $var) {
  430. $var_name = $var['var'];
  431. $tbl_alias = '';
  432. if ($tbl_infos = $this->getVarTableInfos($var_name, 0)) {
  433. $tbl = $tbl_infos['table'];
  434. $col = $tbl_infos['col'];
  435. $tbl_alias = $tbl_infos['table_alias'];
  436. }
  437. elseif ($var_name == 1) {/* ASK query */
  438. $r .= '1 AS `success`';
  439. }
  440. else {
  441. $this->addError('Result variable "' .$var_name. '" not used in query.');
  442. }
  443. if ($tbl_alias) {
  444. /* aggregate */
  445. if ($var['aggregate']) {
  446. $conv_code = '';
  447. if (strtolower($var['aggregate']) != 'count') {
  448. $tbl_alias = 'V_' . $tbl . '_' . $col . '.val';
  449. $conv_code = '0 + ';
  450. }
  451. if (!isset($added[$var['alias']])) {
  452. $r .= $r ? ',' . $nl . ' ' : ' ';
  453. $distinct_code = (strtolower($var['aggregate']) == 'count') && $this->v('distinct', 0, $this->infos['query']) ? 'DISTINCT ' : '';
  454. $r .= $var['aggregate'] . '(' . $conv_code . $distinct_code . $tbl_alias. ') AS `' . $var['alias'] . '`';
  455. $added[$var['alias']] = 1;
  456. }
  457. }
  458. /* normal var */
  459. else {
  460. if (!isset($added[$var_name])) {
  461. $r .= $r ? ',' . $nl . ' ' : ' ';
  462. $r .= $tbl_alias . ' AS `' . $var_name . '`';
  463. $is_s = ($col == 's');
  464. $is_p = ($col == 'p');
  465. $is_o = ($col == 'o');
  466. if ($tbl_alias == 'NULL') {
  467. /* type / add in UNION queries? */
  468. if ($is_s || $is_o) {
  469. $r .= ', ' . $nl . ' NULL AS `' . $var_name . ' type`';
  470. }
  471. /* lang_dt / always add it in UNION queries, the var may be used as s/p/o */
  472. if ($is_o || $this->is_union_query) {
  473. $r .= ', ' . $nl . ' NULL AS `' . $var_name . ' lang_dt`';
  474. }
  475. }
  476. else {
  477. /* type */
  478. if ($is_s || $is_o) {
  479. $r .= ', ' . $nl . ' ' .$tbl_alias . '_type AS `' . $var_name . ' type`';
  480. }
  481. /* lang_dt / always add it in UNION queries, the var may be used as s/p/o */
  482. if ($is_o) {
  483. $r .= ', ' . $nl . ' ' .$tbl_alias . '_lang_dt AS `' . $var_name . ' lang_dt`';
  484. }
  485. elseif ($this->is_union_query) {
  486. $r .= ', ' . $nl . ' NULL AS `' . $var_name . ' lang_dt`';
  487. }
  488. }
  489. $added[$var_name] = 1;
  490. }
  491. }
  492. if (!in_array($tbl_alias, $this->index['sub_joins'])) {
  493. $this->index['sub_joins'][] = $tbl_alias;
  494. }
  495. }
  496. }
  497. return $r ? $r : '1 AS `success`';
  498. }
  499. function getVarTableInfos($var, $ignore_initial_index = 1) {
  500. if ($var == '*') {
  501. return array('table' => '', 'col' => '', 'table_alias' => '*');
  502. }
  503. if ($infos = $this->v($var, 0, $this->index['vars'])) {
  504. $infos[0]['table_alias'] = 'T_' . $infos[0]['table'] . '.' . $infos[0]['col'];
  505. return $infos[0];
  506. }
  507. if ($infos = $this->v($var, 0, $this->index['graph_vars'])) {
  508. $infos[0]['col'] = 'g';
  509. $infos[0]['table_alias'] = 'G_' . $infos[0]['table'] . '.' . $infos[0]['col'];
  510. return $infos[0];
  511. }
  512. if ($this->is_union_query && !$ignore_initial_index) {
  513. if (($infos = $this->v($var, 0, $this->initial_index['vars'])) || ($infos = $this->v($var, 0, $this->initial_index['graph_vars']))) {
  514. if (!in_array($var, $this->infos['null_vars'])) {
  515. $this->infos['null_vars'][] = $var;
  516. }
  517. $infos[0]['table_alias'] = 'NULL';
  518. $infos[0]['col'] = !isset($infos[0]['col']) ? '' : $infos[0]['col'];
  519. return $infos[0];
  520. }
  521. }
  522. return 0;
  523. }
  524. /* */
  525. function getFROMSQL() {
  526. $r = '';
  527. foreach ($this->index['from'] as $id) {
  528. $r .= $r ? ', ' : 'FROM (';
  529. $r .= $this->getTripleTable($id) . ' T_' . $id;
  530. }
  531. return $r ? $r . ')' : '';
  532. }
  533. /* */
  534. function getOrderedJoinIDs() {
  535. return array_merge($this->index['from'], $this->index['join'], $this->index['left_join']);
  536. }
  537. function getJoinInfos($id) {
  538. $r = array();
  539. $tbl_ids = $this->getOrderedJoinIDs();
  540. $pattern = $this->getPattern($id);
  541. foreach ($tbl_ids as $tbl_id) {
  542. $tbl_pattern = $this->getPattern($tbl_id);
  543. if ($tbl_id != $id) {
  544. foreach (array('s', 'p', 'o') as $tbl_term) {
  545. foreach (array('var', 'bnode', 'uri') as $term_type) {
  546. if ($tbl_pattern[$tbl_term . '_type'] == $term_type) {
  547. foreach (array('s', 'p', 'o') as $term) {
  548. if (($pattern[$term . '_type'] == $term_type) && ($tbl_pattern[$tbl_term] == $pattern[$term])) {
  549. $r[] = array('term' => $term, 'join_tbl' => $tbl_id, 'join_term' => $tbl_term);
  550. }
  551. }
  552. }
  553. }
  554. }
  555. }
  556. }
  557. return $r;
  558. }
  559. function getAllJoinsSQL() {
  560. $js = $this->getJoins();
  561. $ljs = $this->getLeftJoins();
  562. $entries = array_merge($js, $ljs);
  563. $id2code = array();
  564. foreach ($entries as $entry) {
  565. if (preg_match('/([^\s]+) ON (.*)/s', $entry, $m)) {
  566. $id2code[$m[1]] = $entry;
  567. }
  568. }
  569. $deps = array();
  570. foreach ($id2code as $id => $code) {
  571. $deps[$id]['rank'] = 0;
  572. foreach ($id2code as $other_id => $other_code) {
  573. $deps[$id]['rank'] += ($id != $other_id) && preg_match('/' . $other_id . '/', $code) ? 1 : 0;
  574. $deps[$id][$other_id] = ($id != $other_id) && preg_match('/' . $other_id . '/', $code) ? 1 : 0;
  575. }
  576. }
  577. $r = '';
  578. do {
  579. /* get next 0-rank */
  580. $next_id = 0;
  581. foreach ($deps as $id => $infos) {
  582. if ($infos['rank'] == 0) {
  583. $next_id = $id;
  584. break;
  585. }
  586. }
  587. if ($next_id) {
  588. $r .= "\n" . $id2code[$next_id];
  589. unset($deps[$next_id]);
  590. foreach ($deps as $id => $infos) {
  591. $deps[$id]['rank'] = 0;
  592. unset($deps[$id][$next_id]);
  593. foreach ($infos as $k => $v) {
  594. if (!in_array($k, array('rank', $next_id))) {
  595. $deps[$id]['rank'] += $v;
  596. $deps[$id][$k] = $v;
  597. }
  598. }
  599. }
  600. }
  601. }
  602. while ($next_id);
  603. if ($deps) {
  604. $this->addError('Not all patterns could be rewritten to SQL JOINs');
  605. }
  606. return $r;
  607. }
  608. function getJoins() {
  609. $r = array();
  610. $nl = "\n";
  611. foreach ($this->index['join'] as $id) {
  612. $sub_r = $this->getJoinConditionSQL($id);
  613. $r[] = 'JOIN ' . $this->getTripleTable($id) . ' T_' . $id . ' ON (' . $sub_r . $nl . ')';
  614. }
  615. foreach (array_merge($this->index['from'], $this->index['join']) as $id) {
  616. if ($sub_r = $this->getRequiredSubJoinSQL($id)) {
  617. $r[] = $sub_r;
  618. }
  619. }
  620. return $r;
  621. }
  622. function getLeftJoins() {
  623. $r = array();
  624. $nl = "\n";
  625. foreach ($this->index['left_join'] as $id) {
  626. $sub_r = $this->getJoinConditionSQL($id);
  627. $r[] = 'LEFT JOIN ' . $this->getTripleTable($id) . ' T_' . $id . ' ON (' . $sub_r . $nl . ')';
  628. }
  629. foreach ($this->index['left_join'] as $id) {
  630. if ($sub_r = $this->getRequiredSubJoinSQL($id, 'LEFT')) {
  631. $r[] = $sub_r;
  632. }
  633. }
  634. return $r;
  635. }
  636. function getJoinConditionSQL($id) {
  637. $r = '';
  638. $nl = "\n";
  639. $infos = $this->getJoinInfos($id);
  640. $pattern = $this->getPattern($id);
  641. $tbl = 'T_' . $id;
  642. /* core dependency */
  643. $d_tbls = $this->getDependentJoins($id);
  644. foreach ($d_tbls as $d_tbl) {
  645. if (preg_match('/^T_([0-9\_]+)\.[spo]+/', $d_tbl, $m) && ($m[1] != $id)) {
  646. if ($this->isJoinedBefore($m[1], $id) && !in_array($m[1], array_merge($this->index['from'], $this->index['join']))) {
  647. $r .= $r ? $nl . ' AND ' : $nl . ' ';
  648. $r .= '(' . $d_tbl . ' IS NOT NULL)';
  649. }
  650. $this->logDependency($id, $d_tbl);
  651. }
  652. }
  653. /* triple-based join info */
  654. foreach ($infos as $info) {
  655. if ($this->isJoinedBefore($info['join_tbl'], $id) && $this->joinDependsOn($id, $info['join_tbl'])) {
  656. $r .= $r ? $nl . ' AND ' : $nl . ' ';
  657. $r .= '(' . $tbl . '.' . $info['term'] . ' = T_' . $info['join_tbl'] . '.' . $info['join_term'] . ')';
  658. }
  659. }
  660. /* filters etc */
  661. if ($sub_r = $this->getPatternSQL($pattern, 'join__T_' . $id)) {
  662. $r .= $r ? $nl . ' AND ' . $sub_r : $nl . ' ' . '(' . $sub_r . ')';
  663. }
  664. return $r;
  665. }
  666. /**
  667. * A log of identified table join dependencies in getJoinConditionSQL
  668. *
  669. */
  670. function logDependency($id, $tbl) {
  671. if (!isset($this->dependency_log[$id])) $this->dependency_log[$id] = array();
  672. if (!in_array($tbl, $this->dependency_log[$id])) {
  673. $this->dependency_log[$id][] = $tbl;
  674. }
  675. }
  676. /**
  677. * checks whether entries in the dependecy log could perhaps be optimized
  678. * (triggers re-ordering of patterns
  679. */
  680. function problematicDependencies() {
  681. foreach ($this->dependency_log as $id => $tbls) {
  682. if (count($tbls) > 1) return count($tbls);
  683. }
  684. return 0;
  685. }
  686. function isJoinedBefore($tbl_1, $tbl_2) {
  687. $tbl_ids = $this->getOrderedJoinIDs();
  688. foreach ($tbl_ids as $id) {
  689. if ($id == $tbl_1) {
  690. return 1;
  691. }
  692. if ($id == $tbl_2) {
  693. return 0;
  694. }
  695. }
  696. }
  697. function joinDependsOn($id, $id2) {
  698. if (in_array($id2, array_merge($this->index['from'], $this->index['join']))) {
  699. return 1;
  700. }
  701. $d_tbls = $this->getDependentJoins($id2);
  702. //echo $id . ' :: ' . $id2 . '=>' . print_r($d_tbls, 1);
  703. foreach ($d_tbls as $d_tbl) {
  704. if (preg_match('/^T_' .$id. '\./', $d_tbl)) {
  705. return 1;
  706. }
  707. }
  708. return 0;
  709. }
  710. function getDependentJoins($id) {
  711. $r = array();
  712. /* sub joins */
  713. foreach ($this->index['sub_joins'] as $alias) {
  714. if (preg_match('/^(T|V|G)_' . $id . '/', $alias)) {
  715. $r[] = $alias;
  716. }
  717. }
  718. /* siblings in shared optional */
  719. $o_id = $this->getOptionalPattern($id);
  720. foreach ($this->index['sub_joins'] as $alias) {
  721. if (preg_match('/^(T|V|G)_' . $o_id . '/', $alias) && !in_array($alias, $r)) {
  722. $r[] = $alias;
  723. }
  724. }
  725. foreach ($this->index['left_join'] as $alias) {
  726. if (preg_match('/^' . $o_id . '/', $alias) && !in_array($alias, $r)) {
  727. $r[] = 'T_' . $alias . '.s';
  728. }
  729. }
  730. return $r;
  731. }
  732. /* */
  733. function getRequiredSubJoinSQL($id, $prefix = '') {/* id is a triple pattern id. Optional FILTERS and GRAPHs are getting added to the join directly */
  734. $nl = "\n";
  735. $r = '';
  736. foreach ($this->index['sub_joins'] as $alias) {
  737. if (preg_match('/^V_' . $id . '_([a-z\_]+)\.val$/', $alias, $m)) {
  738. $col = $m[1];
  739. $sub_r = '';
  740. if ($this->isOptionalPattern($id)) {
  741. $pattern = $this->getPattern($id);
  742. do {
  743. $pattern = $this->getPattern($pattern['parent_id']);
  744. } while ($pattern['parent_id'] && ($pattern['type'] != 'optional'));
  745. $sub_r = $this->getPatternSQL($pattern, 'sub_join__V_' . $id);
  746. }
  747. $sub_r = $sub_r ? $nl . ' AND (' . $sub_r . ')' : '';
  748. /* lang dt only on literals */
  749. if ($col == 'o_lang_dt') {
  750. $sub_sub_r = 'T_' . $id . '.o_type = 2';
  751. $sub_r .= $nl . ' AND (' . $sub_sub_r . ')';
  752. }
  753. //$cur_prefix = $prefix ? $prefix . ' ' : 'STRAIGHT_';
  754. $cur_prefix = $prefix ? $prefix . ' ' : '';
  755. if ($col == 'g') {
  756. $r .= trim($cur_prefix . 'JOIN '. $this->getValueTable($col) . ' V_' .$id . '_' . $col. ' ON (' .$nl. ' (G_' . $id . '.' . $col. ' = V_' . $id. '_' . $col. '.id) ' . $sub_r . $nl . ')');
  757. }
  758. else {
  759. $r .= trim($cur_prefix . 'JOIN '. $this->getValueTable($col) . ' V_' .$id . '_' . $col. ' ON (' .$nl. ' (T_' . $id . '.' . $col. ' = V_' . $id. '_' . $col. '.id) ' . $sub_r . $nl . ')');
  760. }
  761. }
  762. elseif (preg_match('/^G_' . $id . '\.g$/', $alias, $m)) {
  763. $pattern = $this->getPattern($id);
  764. $sub_r = $this->getPatternSQL($pattern, 'graph_sub_join__G_' . $id);
  765. $sub_r = $sub_r ? $nl . ' AND ' . $sub_r : '';
  766. /* dataset restrictions */
  767. $gi = $this->getGraphInfos($id);
  768. $sub_sub_r = '';
  769. $added_gts = array();
  770. foreach ($gi as $set) {
  771. if (isset($set['graph']) && !in_array($set['graph'], $added_gts)) {
  772. $sub_sub_r .= $sub_sub_r !== '' ? ',' : '';
  773. $sub_sub_r .= $this->getTermID($set['graph'], 'g');
  774. $added_gts[] = $set['graph'];
  775. }
  776. }
  777. $sub_r .= ($sub_sub_r !== '') ? $nl . ' AND (G_' . $id . '.g IN (' . $sub_sub_r . '))' : ''; // /* ' . str_replace('#' , '::', $set['graph']) . ' */';
  778. /* other graph join conditions */
  779. foreach ($this->index['graph_vars'] as $var => $occurs) {
  780. $occur_tbls = array();
  781. foreach ($occurs as $occur) {
  782. $occur_tbls[] = $occur['table'];
  783. if ($occur['table'] == $id) break;
  784. }
  785. foreach($occur_tbls as $tbl) {
  786. if (($tbl != $id) && in_array($id, $occur_tbls) && $this->isJoinedBefore($tbl, $id)) {
  787. $sub_r .= $nl . ' AND (G_' .$id. '.g = G_' .$tbl. '.g)';
  788. }
  789. }
  790. }
  791. //$cur_prefix = $prefix ? $prefix . ' ' : 'STRAIGHT_';
  792. $cur_prefix = $prefix ? $prefix . ' ' : '';
  793. $r .= trim($cur_prefix . 'JOIN '. $this->getGraphTable() . ' G_' .$id . ' ON (' .$nl. ' (T_' . $id . '.t = G_' .$id. '.t)' . $sub_r . $nl . ')');
  794. }
  795. }
  796. return $r;
  797. }
  798. /* */
  799. function getWHERESQL() {
  800. $r = '';
  801. $nl = "\n";
  802. /* standard constraints */
  803. $sub_r = $this->getPatternSQL($this->getPattern('0'), 'where');
  804. /* additional constraints */
  805. foreach ($this->index['from'] as $id) {
  806. if ($sub_sub_r = $this->getConstraintSQL($id)) {
  807. $sub_r .= $sub_r ? $nl . ' AND ' . $sub_sub_r : $sub_sub_r;
  808. }
  809. }
  810. $r .= $sub_r ? $sub_r : '';
  811. /* left join dependencies */
  812. foreach ($this->index['left_join'] as $id) {
  813. $d_joins = $this->getDependentJoins($id);
  814. $added = array();
  815. $d_aliases = array();
  816. //echo $id . ' =>' . print_r($d_joins, 1);
  817. $id_alias = 'T_' . $id . '.s';
  818. foreach ($d_joins as $alias) {
  819. if (preg_match('/^(T|V|G)_([0-9\_]+)(_[spo])?\.([a-z\_]+)/', $alias, $m)) {
  820. $tbl_type = $m[1];
  821. $tbl_pattern_id = $m[2];
  822. $suffix = $m[3];
  823. if (($tbl_pattern_id >= $id) && $this->sameOptional($tbl_pattern_id, $id)) {/* get rid of dependency permutations and nested optionals */
  824. if (!in_array($tbl_type . '_' . $tbl_pattern_id . $suffix, $added)) {
  825. $sub_r .= $sub_r ? ' AND ' : '';
  826. $sub_r .= $alias . ' IS NULL';
  827. $d_aliases[] = $alias;
  828. $added[] = $tbl_type . '_' . $tbl_pattern_id . $suffix;
  829. $id_alias = ($tbl_pattern_id == $id) ? $alias : $id_alias;
  830. }
  831. }
  832. }
  833. }
  834. if (count($d_aliases) > 2) {/* @@todo fix this! */
  835. $sub_r1 = ' /* '.$id_alias.' dependencies */';
  836. $sub_r2 = '((' . $id_alias . ' IS NULL) OR (CONCAT(' . join(', ', $d_aliases) . ') IS NOT NULL))';
  837. $r .= $r ? $nl . $sub_r1 . $nl . ' AND ' .$sub_r2 : $sub_r1 . $nl . $sub_r2;
  838. }
  839. }
  840. return $r ? $nl . 'WHERE ' . $r : '';
  841. }
  842. /* */
  843. function addConstraintSQLEntry($id, $sql) {
  844. if (!isset($this->index['constraints'][$id])) {
  845. $this->index['constraints'][$id] = array();
  846. }
  847. if (!in_array($sql, $this->index['constraints'][$id])) {
  848. $this->index['constraints'][$id][] = $sql;
  849. }
  850. }
  851. function getConstraintSQL($id) {
  852. $r = '';
  853. $nl = "\n";
  854. $constraints = $this->v($id, array(), $this->index['constraints']);
  855. foreach ($constraints as $constraint) {
  856. $r .= $r ? $nl . ' AND ' . $constraint : $constraint;
  857. }
  858. return $r;
  859. }
  860. /* */
  861. function getPatternSQL($pattern, $context) {
  862. $type = $pattern['type'];
  863. $m = 'get' . ucfirst($type) . 'PatternSQL';
  864. return method_exists($this, $m) ? $this->$m($pattern, $context) : $this->getDefaultPatternSQL($pattern, $context);
  865. }
  866. function getDefaultPatternSQL($pattern, $context) {
  867. $r = '';
  868. $nl = "\n";
  869. $sub_ids = $this->v('patterns', array(), $pattern);
  870. foreach ($sub_ids as $sub_id) {
  871. $sub_r = $this->getPatternSQL($this->getPattern($sub_id), $context);
  872. $r .= ($r && $sub_r) ? $nl . ' AND (' . $sub_r . ')' : ($sub_r ? $sub_r : '');
  873. }
  874. return $r ? $r : '';
  875. }
  876. function getTriplePatternSQL($pattern, $context) {
  877. $r = '';
  878. $nl = "\n";
  879. $id = $pattern['id'];
  880. /* s p o */
  881. $vars = array();
  882. foreach (array('s', 'p', 'o') as $term) {
  883. $sub_r = '';
  884. $type = $pattern[$term . '_type'];
  885. if ($type == 'uri') {
  886. $term_id = $this->getTermID($pattern[$term], $term);
  887. $sub_r = '(T_' . $id . '.' . $term . ' = ' . $term_id . ') /* ' . str_replace('#' , '::', $pattern[$term]) . ' */';
  888. }
  889. elseif ($type == 'literal') {
  890. $term_id = $this->getTermID($pattern[$term], $term);
  891. $sub_r = '(T_' . $id . '.' . $term . ' = ' . $term_id . ') /* ' . preg_replace('/[\#\n]/' , ' ', $pattern[$term]) . ' */';
  892. if (($lang_dt = $this->v1($term . '_lang', '', $pattern)) || ($lang_dt = $this->v1($term . '_datatype', '', $pattern))) {
  893. $lang_dt_id = $this->getTermID($lang_dt);
  894. $sub_r .= $nl . ' AND (T_' . $id . '.' .$term. '_lang_dt = ' . $lang_dt_id . ') /* ' . str_replace('#' , '::', $lang_dt) . ' */';
  895. }
  896. }
  897. elseif ($type == 'var') {
  898. $val = $pattern[$term];
  899. if (isset($vars[$val])) {/* repeated var in pattern */
  900. $sub_r = '(T_' . $id . '.' . $term . '=' . 'T_' . $id . '.' . $vars[$val] . ')';
  901. }
  902. $vars[$val] = $term;
  903. if ($infos = $this->v($val, 0, $this->index['graph_vars'])) {/* graph var in triple pattern */
  904. $sub_r .= $sub_r ? $nl . ' AND ' : '';
  905. $tbl = $infos[0]['table'];
  906. $sub_r .= 'G_' . $tbl . '.g = T_' . $id . '.' . $term;
  907. }
  908. }
  909. if ($sub_r) {
  910. if (preg_match('/^(join)/', $context) || (preg_match('/^where/', $context) && in_array($id, $this->index['from']))) {
  911. $r .= $r ? $nl . ' AND ' . $sub_r : $sub_r;
  912. }
  913. }
  914. }
  915. /* g */
  916. if ($infos = $pattern['graph_infos']) {
  917. $tbl_alias = 'G_' . $id . '.g';
  918. if (!in_array($tbl_alias, $this->index['sub_joins'])) {
  919. $this->index['sub_joins'][] = $tbl_alias;
  920. }
  921. $sub_r = array('graph_var' => '', 'graph_uri' => '', 'from' => '', 'from_named' => '');
  922. foreach ($infos as $info) {
  923. $type = $info['type'];
  924. if ($type == 'graph') {
  925. if ($info['uri']) {
  926. $term_id = $this->getTermID($info['uri'], 'g');
  927. $sub_r['graph_uri'] .= $sub_r['graph_uri'] ? $nl . ' AND ' : '';
  928. $sub_r['graph_uri'] .= '(' .$tbl_alias. ' = ' . $term_id . ') /* ' . str_replace('#' , '::', $info['uri']) . ' */';
  929. }
  930. }
  931. }
  932. if ($sub_r['from'] && $sub_r['from_named']) {
  933. $sub_r['from_named'] = '';
  934. }
  935. if (!$sub_r['from'] && !$sub_r['from_named']) {
  936. $sub_r['graph_var'] = '';
  937. }
  938. if (preg_match('/^(graph_sub_join)/', $context)) {
  939. foreach ($sub_r as $g_type => $g_sql) {
  940. if ($g_sql) {
  941. $r .= $r ? $nl . ' AND ' . $g_sql : $g_sql;
  942. }
  943. }
  944. }
  945. }
  946. /* optional sibling filters? */
  947. if (preg_match('/^(join|sub_join)/', $context) && $this->isOptionalPattern($id)) {
  948. $o_pattern = $pattern;
  949. do {
  950. $o_pattern = $this->getPattern($o_pattern['parent_id']);
  951. } while ($o_pattern['parent_id'] && ($o_pattern['type'] != 'optional'));
  952. if ($sub_r = $this->getPatternSQL($o_pattern, 'optional_filter' . preg_replace('/^(.*)(__.*)$/', '\\2', $context))) {
  953. $r .= $r ? $nl . ' AND ' . $sub_r : $sub_r;
  954. }
  955. /* created constraints */
  956. if ($sub_r = $this->getConstraintSQL($id)) {
  957. $r .= $r ? $nl . ' AND ' . $sub_r : $sub_r;
  958. }
  959. }
  960. /* result */
  961. if (preg_match('/^(where)/', $context) && $this->isOptionalPattern($id)) {
  962. return '';
  963. }
  964. return $r;
  965. }
  966. /* */
  967. function getFilterPatternSQL($pattern, $context) {
  968. $r = '';
  969. $id = $pattern['id'];
  970. $constraint_id = $this->v1('constraint', '', $pattern);
  971. $constraint = $this->getPattern($constraint_id);
  972. $constraint_type = $constraint['type'];
  973. if ($constraint_type == 'built_in_call') {
  974. $r = $this->getBuiltInCallSQL($constraint, $context);
  975. }
  976. elseif ($constraint_type == 'expression') {
  977. $r = $this->getExpressionSQL($constraint, $context, '', 'filter');
  978. }
  979. else {
  980. $m = 'get' . ucfirst($constraint_type) . 'ExpressionSQL';
  981. if (method_exists($this, $m)) {
  982. $r = $this->$m($constraint, $context, '', 'filter');
  983. }
  984. }
  985. if ($this->isOptionalPattern($id) && !preg_match('/^(join|optional_filter)/', $context)) {
  986. return '';
  987. }
  988. /* unconnected vars in FILTERs eval to false */
  989. $sub_r = $this->hasUnconnectedFilterVars($id);
  990. if ($sub_r) {
  991. if ($sub_r == 'alias') {
  992. if (!in_array($r, $this->index['havings'])) $this->index['havings'][] = $r;
  993. return '';
  994. }
  995. elseif (preg_match('/^T([^\s]+\.)g (.*)$/s', $r, $m)) {/* graph filter */
  996. return 'G' . $m[1] . 't ' . $m[2];
  997. }
  998. elseif (preg_match('/^\(*V[^\s]+_g\.val .*$/s', $r, $m)) {/* graph value filter, @@improveMe */
  999. //return $r;
  1000. }
  1001. else {
  1002. return 'FALSE';
  1003. }
  1004. }
  1005. /* some really ugly tweaks */
  1006. /* empty language filter: FILTER ( lang(?v) = '' ) */
  1007. $r = preg_replace('/\(\/\* language call \*\/ ([^\s]+) = ""\)/s', '((\\1 = "") OR (\\1 LIKE "%:%"))', $r);
  1008. return $r;
  1009. }
  1010. /**
  1011. * Checks if vars in the given (filter) pattern are used within the filter's scope.
  1012. */
  1013. function hasUnconnectedFilterVars($filter_pattern_id) {
  1014. $scope_id = $this->getFilterScope($filter_pattern_id);
  1015. $vars = $this->getFilterVars($filter_pattern_id);
  1016. $r = 0;
  1017. foreach ($vars as $var_name) {
  1018. if ($this->isUsedTripleVar($var_name, $scope_id)) continue;
  1019. if ($this->isAliasVar($var_name)) {
  1020. $r = 'alias';
  1021. break;
  1022. }
  1023. $r = 1;
  1024. break;
  1025. }
  1026. return $r;
  1027. }
  1028. /**
  1029. * Returns the given filter pattern's scope (the id of the parent group pattern).
  1030. */
  1031. function getFilterScope($filter_pattern_id) {
  1032. $patterns = $this->initial_index['patterns'];
  1033. $r = '';
  1034. foreach ($patterns as $id => $p) {
  1035. /* the id has to be sub-part of the given filter id */
  1036. if (!preg_match('/^' . $id . '.+/', $filter_pattern_id)) continue;
  1037. /* we are looking for a group or union */
  1038. if (!preg_match('/^(group|union)$/', $p['type'])) continue;
  1039. /* we are looking for the longest/deepest match */
  1040. if (strlen($id) > strlen($r)) $r = $id;
  1041. }
  1042. return $r;
  1043. }
  1044. /**
  1045. * Builds a list of vars used in the given (filter) pattern.
  1046. */
  1047. function getFilterVars($filter_pattern_id) {
  1048. $r = array();
  1049. $patterns = $this->initial_index['patterns'];
  1050. /* find vars in the given filter (i.e. the given id is part of their pattern id) */
  1051. foreach ($patterns as $id => $p) {
  1052. if (!preg_match('/^' . $filter_pattern_id . '.+/', $id)) continue;
  1053. $var_name = '';
  1054. if ($p['type'] == 'var') {
  1055. $var_name = $p['value'];
  1056. }
  1057. elseif (($p['type'] == 'built_in_call') && ($p['call'] == 'bound')) {
  1058. $var_name = $p['args'][0]['value'];
  1059. }
  1060. if ($var_name && !in_array($var_name, $r)) {
  1061. $r[] = $var_name;
  1062. }
  1063. }
  1064. return $r;
  1065. }
  1066. /**
  1067. * Checks if $var_name appears as result projection alias.
  1068. */
  1069. function isAliasVar($var_name) {
  1070. foreach ($this->infos['query']['result_vars'] as $r_var) {
  1071. if ($r_var['alias'] == $var_name) return 1;
  1072. }
  1073. return 0;
  1074. }
  1075. /**
  1076. * Checks if $var_name is used in a triple pattern in the given scope
  1077. */
  1078. function isUsedTripleVar($var_name, $scope_id = '0') {
  1079. $patterns = $this->initial_index['patterns'];
  1080. foreach ($patterns as $id => $p) {
  1081. if ($p['type'] != 'triple') continue;
  1082. if (!preg_match('/^' . $scope_id . '.+/', $id)) continue;
  1083. foreach (array('s', 'p', 'o') as $term) {
  1084. if ($p[$term . '_type'] != 'var') continue;
  1085. if ($p[$term] == $var_name) return 1;
  1086. }
  1087. }
  1088. }
  1089. /* */
  1090. function getExpressionSQL($pattern, $context, $val_type = '', $parent_type = '') {
  1091. $r = '';
  1092. $nl = "\n";
  1093. $type = $this->v1('type', '', $pattern);
  1094. $sub_type = $this->v1('sub_type', $type, $pattern);
  1095. if (preg_match('/^(and|or)$/', $sub_type)) {
  1096. foreach ($pattern['patterns'] as $sub_id) {
  1097. $sub_pattern = $this->getPattern($sub_id);
  1098. $sub_pattern_type = $sub_pattern['type'];
  1099. if ($sub_pattern_type == 'built_in_call') {
  1100. $sub_r = $this->getBuiltInCallSQL($sub_pattern, $context, '', $parent_type);
  1101. }
  1102. else {
  1103. $sub_r = $this->getExpressionSQL($sub_pattern, $context, '', $parent_type);
  1104. }
  1105. if ($sub_r) {
  1106. $r .= $r ? ' ' . strtoupper($sub_type). ' (' .$sub_r. ')' : '(' . $sub_r . ')';
  1107. }
  1108. }
  1109. }
  1110. elseif ($sub_type == 'built_in_call') {
  1111. $r = $this->getBuiltInCallSQL($pattern, $context, $val_type, $parent_type);
  1112. }
  1113. elseif (preg_match('/literal/', $sub_type)) {
  1114. $r = $this->getLiteralExpressionSQL($pattern, $context, $val_type, $parent_type);
  1115. }
  1116. elseif ($sub_type) {
  1117. $m = 'get' . ucfirst($sub_type) . 'ExpressionSQL';
  1118. if (method_exists($this, $m)) {
  1119. $r = $this->$m($pattern, $context, '', $parent_type);
  1120. }
  1121. }
  1122. /* skip expressions that reference non-yet-joined tables */
  1123. if (preg_match('/__(T|V|G)_(.+)$/', $context, $m)) {
  1124. $context_pattern_id = $m[2];
  1125. $context_table_type = $m[1];
  1126. if (preg_match_all('/((T|V|G)(\_[0-9])+)/', $r, $m)) {
  1127. $aliases = $m[1];
  1128. $keep = 1;
  1129. foreach ($aliases as $alias) {
  1130. if (preg_match('/(T|V|G)_(.*)$/', $alias, $m)) {
  1131. $tbl_type = $m[1];
  1132. $tbl = $m[2];
  1133. if (!$this->isJoinedBefore($tbl, $context_pattern_id)) {
  1134. $keep = 0;
  1135. }
  1136. elseif (($context_pattern_id == $tbl) && preg_match('/(TV)/', $context_table_type . $tbl_type)) {
  1137. $keep = 0;
  1138. }
  1139. }
  1140. }
  1141. $r = $keep ? $r : '';
  1142. }
  1143. }
  1144. return $r ? '(' . $r . ')' : $r;
  1145. }
  1146. function detectExpressionValueType($pattern_ids) {
  1147. foreach ($pattern_ids as $id) {
  1148. $pattern = $this->getPattern($id);
  1149. $type = $this->v('type', '', $pattern);
  1150. if (($type == 'literal') && isset($pattern['datatype'])) {
  1151. if (in_array($pattern['datatype'], array($this->xsd . 'integer', $this->xsd . 'float', $this->xsd . 'double'))) {
  1152. return 'numeric';
  1153. }
  1154. }
  1155. }
  1156. return '';
  1157. }
  1158. /* */
  1159. function getRelationalExpressionSQL($pattern, $context, $val_type = '', $parent_type = '') {
  1160. $r = '';
  1161. $val_type = $this->detectExpressionValueType($pattern['patterns']);
  1162. $op = $pattern['operator'];
  1163. foreach ($pattern['patterns'] as $sub_id) {
  1164. $sub_pattern = $this->getPattern($sub_id);
  1165. $sub_pattern['parent_op'] = $op;
  1166. $sub_type = $sub_pattern['type'];
  1167. $m = ($sub_type == 'built_in_call') ? 'getBuiltInCallSQL' : 'get' . ucfirst($sub_type) . 'ExpressionSQL';
  1168. $m = str_replace('ExpressionExpression', 'Expression', $m);
  1169. $sub_r = method_exists($this, $m) ? $this->$m($sub_pattern, $context, $val_type, 'relational') : '';
  1170. $r .= $r ? ' ' . $op . ' ' . $sub_r : $sub_r;
  1171. }
  1172. return $r ? '(' . $r . ')' : $r;
  1173. }
  1174. function getAdditiveExpressionSQL($pattern, $context, $val_type = '', $parent_type = '') {
  1175. $r = '';
  1176. $val_type = $this->detectExpressionValueType($pattern['patterns']);
  1177. foreach ($pattern['patterns'] as $sub_id) {
  1178. $sub_pattern = $this->getPattern($sub_id);
  1179. $sub_type = $this->v('type', '', $sub_pattern);
  1180. $m = ($sub_type == 'built_in_call') ? 'getBuiltInCallSQL' : 'get' . ucfirst($sub_type) . 'ExpressionSQL';
  1181. $m = str_replace('ExpressionExpression', 'Expression', $m);
  1182. $sub_r = method_exists($this, $m) ? $this->$m($sub_pattern, $context, $val_type, 'additive') : '';
  1183. $r .= $r ? ' ' . $sub_r : $sub_r;
  1184. }
  1185. return $r;
  1186. }
  1187. function getMultiplicativeExpressionSQL($pattern, $context, $val_type = '', $parent_type = '') {
  1188. $r = '';
  1189. $val_type = $this->detectExpressionValueType($pattern['patterns']);
  1190. foreach ($pattern['patterns'] as $sub_id) {
  1191. $sub_pattern = $this->getPattern($sub_id);
  1192. $sub_type = $sub_pattern['type'];
  1193. $m = ($sub_type == 'built_in_call') ? 'getBuiltInCallSQL' : 'get' . ucfirst($sub_type) . 'ExpressionSQL';
  1194. $m = str_replace('ExpressionExpression', 'Expression', $m);
  1195. $sub_r = method_exists($this, $m) ? $this->$m($sub_pattern, $context, $val_type, 'multiplicative') : '';
  1196. $r .= $r ? ' ' . $sub_r : $sub_r;
  1197. }
  1198. return $r;
  1199. }
  1200. /* */
  1201. function getVarExpressionSQL($pattern, $context, $val_type = '', $parent_type = '') {
  1202. $var = $pattern['value'];
  1203. $info = $this->getVarTableInfos($var);
  1204. if (!$tbl = $info['table']) {
  1205. /* might be an aggregate var */
  1206. $vars = $this->infos['query']['result_vars'];
  1207. foreach ($vars as $test_var) {
  1208. if ($test_var['alias'] == $pattern['value']) {
  1209. return '`' . $pattern['value'] . '`';
  1210. }
  1211. }
  1212. return '';
  1213. }
  1214. $col = $info['col'];
  1215. if (($context == 'order') && ($col == 'o')) {
  1216. $tbl_alias = 'T_' . $tbl . '.o_comp';
  1217. }
  1218. elseif ($context == 'sameterm') {
  1219. $tbl_alias = 'T_' . $tbl . '.' . $col;
  1220. }
  1221. elseif (($parent_type == 'relational') && ($col == 'o') && (preg_match('/[\<\>]/', $this->v('parent_op', '', $pattern)))) {
  1222. $tbl_alias = 'T_' . $tbl . '.o_comp';
  1223. }
  1224. else {
  1225. $tbl_alias = 'V_' . $tbl . '_' . $col . '.val';
  1226. if (!in_array($tbl_alias, $this->index['sub_joins'])) {
  1227. $this->index['sub_joins'][] = $tbl_alias;
  1228. }
  1229. }
  1230. $op = $this->v('operator', '', $pattern);
  1231. if (preg_match('/^(filter|and)/', $parent_type)) {
  1232. if ($op == '!') {
  1233. $r = '(((' . $tbl_alias . ' = 0) AND (CONCAT("1", ' . $tbl_alias . ') != 1))'; /* 0 and no string */
  1234. $r .= ' OR (' . $tbl_alias . ' IN ("", "false")))'; /* or "", or "false" */
  1235. }
  1236. else {
  1237. $r = '((' . $tbl_alias . ' != 0)'; /* not null */
  1238. $r .= ' OR ((CONCAT("1", ' . $tbl_alias . ') = 1) AND (' . $tbl_alias . ' NOT IN ("", "false"))))'; /* string, and not "" or "false" */
  1239. }
  1240. }
  1241. else {
  1242. $r = trim($op . ' ' . $tbl_alias);
  1243. if ($val_type == 'numeric') {
  1244. if (preg_match('/__(T|V|G)_(.+)$/', $context, $m)) {
  1245. $context_pattern_id = $m[2];
  1246. $context_table_type = $m[1];
  1247. }
  1248. else {
  1249. $context_pattern_id = $pattern['id'];
  1250. $context_table_type = 'T';
  1251. }
  1252. if ($this->isJoinedBefore($tbl, $context_pattern_id)) {
  1253. $add = ($tbl != $context_pattern_id) ? 1 : 0;
  1254. $add = (!$add && ($context_table_type == 'V')) ? 1 : 0;
  1255. if ($add) {
  1256. $this->addConstraintSQLEntry($context_pattern_id, '(' .$r. ' = "0" OR ' . $r . '*1.0 != 0)');
  1257. }
  1258. }
  1259. }
  1260. }
  1261. return $r;
  1262. }
  1263. /* */
  1264. function getUriExpressionSQL($pattern, $context, $val_type = '') {
  1265. $val = $pattern['uri'];
  1266. $r = $pattern['operator'];
  1267. $r .= is_numeric($val) ? ' ' . $val : ' "' . mysql_real_escape_string($val, $this->store->getDBCon()) . '"';
  1268. return $r;
  1269. }
  1270. /* */
  1271. function getLiteralExpressionSQL($pattern, $context, $val_type = '', $parent_type = '') {
  1272. $val = $pattern['value'];
  1273. $r = $pattern['operator'];
  1274. if (is_numeric($val) && $this->v('datatype', 0, $pattern)) {
  1275. $r .= ' ' . $val;
  1276. }
  1277. elseif (preg_match('/^(true|false)$/i', $val) && ($this->v1('datatype', '', $pattern) == 'http://www.w3.org/2001/XMLSchema#boolean')) {
  1278. $r .= ' ' . strtoupper($val);
  1279. }
  1280. elseif ($parent_type == 'regex') {
  1281. $sub_r = mysql_real_escape_string($val, $this->store->getDBCon());
  1282. $r .= ' "' . preg_replace('/\x5c\x5c/', '\\', $sub_r) . '"';
  1283. }
  1284. else {
  1285. $r .= ' "' . mysql_real_escape_string($val, $this->store->getDBCon()) . '"';
  1286. }
  1287. if (($lang_dt = $this->v1('lang', '', $pattern)) || ($lang_dt = $this->v1('datatype', '', $pattern))) {
  1288. /* try table/alias via var in siblings */
  1289. if ($var = $this->findSiblingVarExpression($pattern['id'])) {
  1290. if (isset($this->index['vars'][$var])) {
  1291. $infos = $this->index['vars'][$var];
  1292. foreach ($infos as $info) {
  1293. if ($info['col'] == 'o') {
  1294. $tbl = $info['table'];
  1295. $term_id = $this->getTermID($lang_dt);
  1296. if ($pattern['operator'] != '!=') {
  1297. if (preg_match('/__(T|V|G)_(.+)$/', $context, $m)) {
  1298. $context_pattern_id = $m[2];
  1299. $context_table_type = $m[1];
  1300. }
  1301. elseif ($context == 'where') {
  1302. $context_pattern_id = $tbl;
  1303. }
  1304. else {
  1305. $context_pattern_id = $pattern['id'];
  1306. }
  1307. if ($tbl == $context_pattern_id) {/* @todo better dependency check */
  1308. if ($term_id || ($lang_dt != 'http://www.w3.org/2001/XMLSchema#integer')) {/* skip if simple int, but no id */
  1309. $this->addConstraintSQLEntry($context_pattern_id, 'T_' . $tbl . '.o_lang_dt = ' . $term_id . ' /* ' . str_replace('#' , '::', $lang_dt) . ' */');
  1310. }
  1311. }
  1312. }
  1313. break;
  1314. }
  1315. }
  1316. }
  1317. }
  1318. }
  1319. return trim($r);
  1320. }
  1321. function findSiblingVarExpression($id) {
  1322. $pattern = $this->getPattern($id);
  1323. do {
  1324. $pattern = $this->getPattern($pattern['parent_id']);
  1325. } while ($pattern['parent_id'] && ($pattern['type'] != 'expression'));
  1326. $sub_patterns = $this->v('patterns', array(), $pattern);
  1327. foreach ($sub_patterns as $sub_id) {
  1328. $sub_pattern = $this->getPattern($sub_id);
  1329. if ($sub_pattern['type'] == 'var') {
  1330. return $sub_pattern['value'];
  1331. }
  1332. }
  1333. return '';
  1334. }
  1335. /* */
  1336. function getFunctionExpressionSQL($pattern, $contex

Large files files are truncated, but you can click here to view the full file