PageRenderTime 69ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/DemiBlog/lib/arc/store/ARC2_StoreSelectQueryHandler.php

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

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