PageRenderTime 59ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/v1/mod_semanticweb/arc/store/ARC2_StoreSelectQueryHandler.php

https://code.google.com/p/goodrelations-for-joomla/
PHP | 1628 lines | 1428 code | 109 blank | 91 comment | 353 complexity | ee98601b79dd6df5f4c8fc7cce61fcdc MD5 | raw file

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

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

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