AclQueryBuilder.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. <?php
  2. Lib::loadClass('P5');
  3. Lib::loadClass('Core_AclBase');
  4. Lib::loadClass('AntAclBase');
  5. Lib::loadClass('ACL');
  6. class AclQueryBuilder {
  7. public $select;
  8. public $from;
  9. public $where;
  10. /* where: array of [ $fieldName, $comparisonSign, $value ]
  11. * $fieldName - field name, TODO: xpath, null for groups (or, and)
  12. * $comparisonSign - @see where() to check allowed (implemented) signs or function names
  13. * $value - string or another $where if group (or, and)
  14. * where examples: [ $fieldName, $comparisonSign, $value ]
  15. [ 'ID', '=', '1' ] // where ID = '1'
  16. [ 'LABEL', 'like', '%abc%' ] // where LABEL like '%abc%'
  17. [ null, 'or', [] $values ] // where ( $values[0] or $values[1] or ... ) // or where $values[0] when 1 === count($values)
  18. [ null, 'and', [] $values ] // where ( $values[0] and $values[1] and ... ) // or where $values[0] when 1 === count($values)
  19. */
  20. public $orderBy;
  21. public $groupBy;
  22. public $limit;
  23. public $offset;
  24. public $_fromPrefix;
  25. public $_joinPrefix;
  26. public $_joinParams;
  27. public $_joinType;
  28. public $isInstances;
  29. public $isNotInstances;
  30. public $_hasSelectRemoteFields;
  31. public $_hasQueryRemoteFields;
  32. public function __construct() {
  33. $this->select = [];
  34. $this->from = null; // (ACL | tableName)
  35. $this->where = [];
  36. $this->orderBy = null;
  37. $this->groupBy = null;
  38. $this->limit = null;
  39. $this->offset = null;
  40. $this->_fromPrefix = 't'; // prefix for this->from - default 't'
  41. $this->_joinPrefix = []; // prefix => from (Acl | tableName)
  42. $this->_joinParams = []; // prefx => params
  43. $this->_joinType = []; // prefix => ( 'join' | 'left join' )
  44. $this->isInstances = [];
  45. $this->isNotInstances = [];
  46. $this->_hasSelectRemoteFields = false;
  47. $this->_hasQueryRemoteFields = false;
  48. }
  49. public function from($from, $prefix = 't') {
  50. // DBG::log([
  51. // 'from instanceof Core_AclBase' => ($from instanceof Core_AclBase),
  52. // 'from instanceof AntAclBase' => ($from instanceof AntAclBase),
  53. // 'from instanceof TableAcl' => ($from instanceof TableAcl),
  54. // '$from' => $from
  55. // ], 'array', "\$from class(".get_class($from).")");
  56. if ($this->from) throw new Exception("Duplicate FROM");
  57. $this->from = $from;
  58. $this->_fromPrefix = $prefix;
  59. return $this;
  60. }
  61. public function select($propertyName) { // TODO: ogc:propertyName, *, xpath, @instances, etc...
  62. if (empty($propertyName)) return $this; // SKIP empty values, null's, etc.
  63. DBG::log($propertyName, 'array', "AclQueryBuilder->select");
  64. if (is_array($propertyName)) {
  65. $hasWildcard = in_array('*', $propertyName);
  66. foreach ($propertyName as $k => $v) {
  67. if ('rawSelect' === $k) $this->select['__rawSelect__'] = $v;
  68. else if ('*' === $v) continue;
  69. else $this->select[] = $v;
  70. }
  71. if ($hasWildcard) array_unshift($this->select, '*');
  72. return $this;
  73. }
  74. if (!in_array($propertyName, $this->select)) $this->select[] = $propertyName; // TODO: split by property source
  75. return $this;
  76. }
  77. public function where($where) {
  78. if (null === $where) return $this;
  79. if (is_string($where)) return $this->whereRaw($where);
  80. list($fieldName, $comparisonSign, $value) = $where;
  81. if (!in_array($comparisonSign, [ // validation
  82. '=', '<', '>', '<=', '>=', '<>', '!='
  83. , 'like', 'not like'
  84. , 'is not null', 'is null'
  85. , 'Intersects', 'GeometryType'
  86. , 'or' // $value = [ comparisons for $fieldName ... or null ]
  87. , 'and' // $value = [ comparisons for $fieldName ... or null ]
  88. ])) {
  89. throw new Exception("Not implemented comparisonSign '{$comparisonSign}'");
  90. }
  91. $this->where[] = [$fieldName, $comparisonSign, $value];
  92. return $this;
  93. }
  94. public function _generateWhereMain($where) { // @returns string
  95. if (is_string($where)) return $where; // whereRaw
  96. list($prefixedFieldName, $comparisonSign, $value) = $where;
  97. // $sqlFieldName = $fieldName; // TODO: getSqlFieldName // TODO: get sql field name with table prefix from join list to replace "{$this->_fromPrefix}.{$sqlFieldName}" below
  98. $prefixedFieldName = (false === strpos($prefixedFieldName, '.')) ? "{$this->_fromPrefix}.{$prefixedFieldName}" : $prefixedFieldName;
  99. list($prefix, $fieldName) = explode('.', $prefixedFieldName);
  100. $sqlPrefix = $this->getPDO()->identifierQuote($prefix);
  101. $sqlFieldName = $this->getPDO()->identifierQuote($fieldName);
  102. switch ($comparisonSign) {
  103. case 'is not null': return "{$sqlPrefix}.{$sqlFieldName} is not null";
  104. case 'is null': return "{$sqlPrefix}.{$sqlFieldName} is null";
  105. case 'Intersects': return "Intersects(GeomFromText('{$value}'), {$sqlPrefix}.{$sqlFieldName})=1";
  106. case 'GeometryType': return "GeometryType({$sqlPrefix}.{$sqlFieldName})='{$value}'";
  107. case 'or': return $this->_generateWhereBlock($where);
  108. case 'and': return $this->_generateWhereBlock($where);
  109. case 'UNIX_TIMESTAMP_LESS_THAN_NOW': return "
  110. COALESCE(UNIX_TIMESTAMP({$sqlPrefix}.{$sqlFieldName}), 0) < UNIX_TIMESTAMP()
  111. and {$sqlPrefix}.{$sqlFieldName} != ''
  112. and {$sqlPrefix}.{$sqlFieldName} != '0000-00-00 00:00:00'
  113. ";
  114. case 'UNIX_TIMESTAMP_NOW_3600': return "
  115. COALESCE(UNIX_TIMESTAMP({$sqlPrefix}.{$sqlFieldName}), 0) < UNIX_TIMESTAMP()+3600
  116. and COALESCE(UNIX_TIMESTAMP({$sqlPrefix}.{$sqlFieldName}), 0) > UNIX_TIMESTAMP()-3600
  117. ";
  118. case 'UNIX_TIMESTAMP_GREATER_THAN': return " COALESCE(UNIX_TIMESTAMP({$sqlPrefix}.{$sqlFieldName}), 0) > '{$value}' ";
  119. case 'UNIX_TIMESTAMP_LESS_THAN': return " COALESCE(UNIX_TIMESTAMP({$sqlPrefix}.{$sqlFieldName}), 0) < '{$value}' ";
  120. default: return "{$sqlPrefix}.{$sqlFieldName} {$comparisonSign} " . $this->getPDO()->quote($value);
  121. }
  122. return null;
  123. }
  124. public function _generateWhereBlock($where) { // @returns string
  125. list($fieldName, $sqlGlue, $list) = $where;
  126. $list = array_filter($list, function ($value) { return null !== $value; });
  127. $sqlList = array_filter(
  128. array_map([$this, '_generateWhereMain'], $list),
  129. 'is_string'
  130. );
  131. if (1 === count($sqlList)) return $sqlList[0];
  132. else return "( " . implode(" {$sqlGlue} ", $sqlList) . " )";
  133. }
  134. public function whereIsNotNull($fieldName) {
  135. $this->where[] = "{$this->_fromPrefix}.{$fieldName} is not null";
  136. return $this;
  137. }
  138. public function whereRaw($rawWhere) { // add where without validation
  139. if (!$rawWhere) return $this;
  140. $this->where[] = $rawWhere;
  141. return $this;
  142. }
  143. // public function whereFunction($column, $operator = null, $value = null) {
  144. public function whereFunction($fieldName, $comparisonSign = null, $value = null) {
  145. throw new Exception("whereFunction not supported");
  146. $this->where[] = '';
  147. return $this;
  148. }
  149. public function generateWhereSql() { // @return string - sql without where keyword
  150. $sqlWhere = array_filter(
  151. array_map([$this, '_generateWhereMain'], $this->where),
  152. 'is_string'
  153. );
  154. return (!empty($sqlWhere)) ? implode("\n\t and ", $sqlWhere) : '';
  155. }
  156. public function _generateSelectMain($select, $key) {
  157. if ('__rawSelect__' === $key) return $select;
  158. $sqlPk = 'ID';
  159. if ($this->from instanceof Core_AclBase) $sqlPk = $this->from->getSqlPrimaryKeyField();
  160. if ('*' === $select) return "{$this->_fromPrefix}.*";
  161. if ('@primaryKey' === $select) {
  162. return "{$this->_fromPrefix}.{$sqlPk} as " . $this->getPDO()->identifierQuote("@primaryKey");
  163. }
  164. if ('@instances' === $select) {
  165. if (!($this->from instanceof Core_AclBase)) throw new Exception("select @instances allowed only for Acl object");
  166. // TODO: fetch list possible instances, get all instance table name
  167. // group_concat(
  168. // > foreach ($listInstanceConfig as $instanceConfig) {
  169. // IF( ( select 1 from `{$instanceTable}` where ID = {$this->_fromPrefix}.{$sqlPk} ) > 0, '{$instanceName},', ''),
  170. // )
  171. return " '' as " . $this->getPDO()->identifierQuote("@instances");
  172. }
  173. if (is_array($select)) {
  174. // TODO: [ '__backRef' => [ ... ] ]
  175. DBG::log($select, 'array', "TODO: select array");
  176. return null;
  177. }
  178. if (is_string($select)) {
  179. // TODO: only real table field
  180. // TODO: if geometry type then `AsWKT(t.{$sqlFieldName}) as {$fieldName}`
  181. try {
  182. return $this->parseSelectFieldValueToSql($select, $this->_fromPrefix);
  183. } catch (Exception $e) {
  184. DBG::log($e);
  185. }
  186. }
  187. return null;
  188. }
  189. public function join($remoteTableName, $prefix, $params) {
  190. if (array_key_exists($prefix, $this->_joinPrefix)) throw new Exception("Prefix already used!");
  191. $this->_joinPrefix[$prefix] = $remoteTableName;
  192. $this->_joinParams[$prefix] = $params;
  193. $this->_joinType[$prefix] = 'join';
  194. return $this;
  195. }
  196. public function leftJoin($remoteTableName, $prefix, $params) {
  197. if (array_key_exists($prefix, $this->_joinPrefix)) throw new Exception("Prefix already used!");
  198. $this->_joinPrefix[$prefix] = $remoteTableName;
  199. $this->_joinParams[$prefix] = $params;
  200. $this->_joinType[$prefix] = 'left join';
  201. return $this;
  202. }
  203. public function orderBy($orderBy) { // TODO: ogc: order by ...
  204. if (null !== $this->orderBy) throw new Exception("OrderBy already set!");
  205. $this->orderBy = [];
  206. if (!$orderBy) return $this;
  207. // ID A,COL_X D,COL_Y A,...
  208. if (false !== strpos($orderBy, '+')) $orderBy = str_replace('+', ' ', $orderBy);
  209. $sortByEx = array_map('trim', explode(',', $orderBy));
  210. $sortByEx = array_filter($sortByEx, ['V', 'filterNotEmpty']);
  211. foreach ($sortByEx as $sortPart) {
  212. $sortPartEx = explode(' ', $sortPart);
  213. if (count($sortPartEx) > 2) throw new Exception("SortBy parse error #" . __LINE__);
  214. $fieldName = trim($sortPartEx[0]);
  215. if (!$this->isFieldAllowedToOrderBy($fieldName)) throw new Exception("SortBy parse error for field '{$fieldName}' #" . __LINE__);
  216. $colSortDir = 'ASC';
  217. if (count($sortPartEx) == 2) {
  218. if ('A' == strtoupper($sortPartEx[1]) || 'ASC' == strtoupper($sortPartEx[1])) {
  219. } else if ('D' == strtoupper($sortPartEx[1]) || 'DESC' == strtoupper($sortPartEx[1])) {
  220. $colSortDir = 'DESC';
  221. } else throw new Exception("SortBy parse error - unknown sort order '{$sortPartEx[1]}' #" . __LINE__);
  222. }
  223. $this->orderBy[] = [$fieldName, $colSortDir];
  224. DBG::log($this->orderBy, 'array', "sortBy");
  225. }
  226. return $this;
  227. }
  228. public function isFieldAllowedToOrderBy($fieldName) {
  229. return true; // TODO:? only local fields in $this->from
  230. }
  231. public function generateOrderBySql() {
  232. if (empty($this->orderBy)) return '';
  233. $sortByList = [];
  234. foreach ($this->orderBy as $orderBy) {
  235. list($fieldName, $orderDir) = $orderBy;
  236. if (false !== strpos($fieldName, '.')) {
  237. list($joinPrefix, $joinFieldName) = explode('.', $fieldName, 2);
  238. $sqlOrderByField = $this->getPDO()->identifierQuote($joinFieldName);
  239. if ('t' !== $joinPrefix && !array_key_exists($joinPrefix, $this->_joinParams)) throw new Exception("Missing table prefix '{$joinPrefix}' in orderBy");
  240. $sortByList[] = "{$joinPrefix}.{$sqlOrderByField} {$orderDir}";
  241. } else {
  242. $sqlOrderByField = $this->getPDO()->identifierQuote($fieldName);
  243. $sortByList[] = "t.{$sqlOrderByField} {$orderDir}";
  244. }
  245. }
  246. return (!empty($sortByList))
  247. ? "order by " . implode(", ", $sortByList)
  248. : '';
  249. }
  250. public function limit($limit) {
  251. $this->limit = (int)$limit;
  252. return $this;
  253. }
  254. public function offset($offset) {
  255. $this->offset = (int)$offset;
  256. return $this;
  257. }
  258. public function isInstance($instances) {
  259. $this->isInstances = (is_array($instances)) ? $instances : [ $instances ];
  260. return $this;
  261. }
  262. public function isNotInstance($instances) {
  263. $this->isNotInstances = (is_array($instances)) ? $instances : [ $instances ];
  264. return $this;
  265. }
  266. public function _parseJoinParams($params) {
  267. if (array_key_exists('rawJoin', $params)) return $params['rawJoin'];
  268. throw new Exception("Not implemented JOIN params '".json_encode($params)."'");
  269. }
  270. public function _getTableName($source) {
  271. if (is_scalar($source)) return $source;
  272. if ($source instanceof Core_AclBase) return $source->getRootTableName();
  273. throw new Exception("Not implemented FROM type '".get_class($source)."'");
  274. }
  275. public function execute() {
  276. return $this->fetchAll();
  277. }
  278. public function getPDO() {
  279. $idDatabase = $this->from->getDB();
  280. return DB::getPDO($idDatabase);
  281. }
  282. public function fetchAll() {
  283. DBG::log("AclQueryBuilder::fetchAll - generateSql... ns(".$this->from->getNamespace().")");
  284. $sql = $this->generateSql();
  285. DBG::log("AclQueryBuilder::fetchAll - generateSql end ns(".$this->from->getNamespace().")");
  286. return $this->getPDO()->fetchAll($sql);
  287. }
  288. public function fetchTotal() {
  289. $sql = $this->generateSql("count(*) as cnt");
  290. return $this->getPDO()->fetchValue($sql);
  291. }
  292. public function fetchValue() {
  293. $sql = $this->generateSql();
  294. DBG::log(['sql'=>$sql,'this'=>(array)$this], 'array', "AclQueryBuilder::fetchValue");
  295. return $this->getPDO()->fetchValue($sql);
  296. }
  297. public function fetchFirst() {
  298. $sql = $this->generateSql();
  299. DBG::log(['sql'=>$sql,'this'=>(array)$this], 'array', "AclQueryBuilder::fetchFirst");
  300. return $this->getPDO()->fetchFirst($sql);
  301. }
  302. public function generateSql($select = null) {
  303. if (!$this->from) throw new Exception("Missing FROM");
  304. $tableName = $this->_getTableName($this->from);
  305. if (!$tableName) throw new Exception("Missing FROM table name");
  306. $sqlPk = ($this->from instanceof Core_AclBase)
  307. ? $this->from->getSqlPrimaryKeyField()
  308. : 'ID';
  309. $sqlJoin = [];
  310. DBG::log($this, 'array', '$this');
  311. foreach ($this->isInstances as $k => $ns) {
  312. $instanceConf = ACL::getInstanceConfig($ns);
  313. $sqlInstPrefix = "inst_{$instanceConf->id}_is";
  314. DBG::log($instanceConf, 'array', "DBG: \$instanceConf");
  315. $sqlJoin[] = " join `{$instanceConf->tableName}` `{$sqlInstPrefix}` on(`{$sqlInstPrefix}`.ID = {$this->_fromPrefix}.{$sqlPk}) ";
  316. }
  317. foreach ($this->isNotInstances as $k => $ns) {
  318. $instanceConf = ACL::getInstanceConfig($ns);
  319. $sqlInstPrefix = "inst_{$instanceConf->id}_is_not";
  320. $sqlJoin[] = " left join `{$instanceConf->tableName}` `{$sqlInstPrefix}` on(`{$sqlInstPrefix}`.ID = {$this->_fromPrefix}.{$sqlPk}) ";
  321. $this->where[] = " `{$sqlInstPrefix}`.ID IS NULL "; // TODO: use view
  322. }
  323. foreach ($this->_joinPrefix as $prefix => $join) {
  324. $joinName = $this->_getTableName($join);
  325. $sqlJoin[] = " {$this->_joinType[$prefix]} `{$joinName}` {$prefix} on(" . $this->_parseJoinParams($this->_joinParams[$prefix]) . ") ";
  326. }
  327. $sqlJoin = (!empty($sqlJoin)) ? implode("\n\t", $sqlJoin) : "";
  328. DBG::log($this->where, 'array', "generateSql \$this->where");
  329. $sqlWhere = array_filter(
  330. array_map([$this, '_generateWhereMain'], $this->where),
  331. 'is_string'
  332. );
  333. $sqlWhere = (!empty($sqlWhere)) ? "where " . implode("\n\t and ", $sqlWhere) : '';
  334. DBG::log($sqlWhere, 'array', "generateSql \$sqlWhere");
  335. $limit = ($this->limit < 0) ? 0 : $this->limit;
  336. $offset = ($this->offset < 0) ? 0 : $this->offset;
  337. $sqlLimit = ($limit > 0) ? "limit {$limit} offset {$offset}" : '';
  338. // TODO: split select to local and remote (use field isLocal)
  339. // TODO: $this->_hasSelectRemoteFields = false;
  340. // TODO: $this->_hasQueryRemoteFields = false;
  341. if ($select) {
  342. $sqlSelect = $select; // used for example fetchTotal -> generateSql("count(*) as cnt")
  343. } else {
  344. $sqlSelect = array_filter(
  345. array_map([$this, '_generateSelectMain'], $this->select, array_keys($this->select)),
  346. 'is_string'
  347. );
  348. $sqlSelect = (!empty($sqlSelect))
  349. ? implode(",\n\t", $sqlSelect)
  350. : "{$this->_fromPrefix}.*"
  351. ;
  352. }
  353. $sqlOrderBy = $this->generateOrderBySql();
  354. $sqlTableName = (is_object($this->from) && method_exists($this->from, 'getSqlTableFrom'))
  355. ? $this->from->getSqlTableFrom()
  356. : $this->getPDO()->tableNameQuote( $tableName );
  357. return "
  358. select {$sqlSelect}
  359. from {$sqlTableName} {$this->_fromPrefix}
  360. {$sqlJoin}
  361. {$sqlWhere}
  362. {$sqlOrderBy}
  363. {$sqlLimit}
  364. ";
  365. }
  366. public function parseSelectFieldValueToSql($fieldName, $prefix = 't') {
  367. if (false !== strpos($fieldName, '/')) {
  368. DBG::log($fieldName, 'string', "TODO: select by xpath");
  369. throw new Exception("Not implemented select by xpath ('{$fieldName}')");
  370. }
  371. $fieldType = $this->from->getXsdFieldType($fieldName);
  372. @list($typePrefix, $typeName, $retTypeName) = explode(':', $fieldType);
  373. $sqlFieldName = $this->getPDO()->identifierQuote($fieldName);
  374. switch ($typePrefix) {
  375. case 'xsd': {
  376. switch ($typeName) {
  377. case 'base64Binary': return "IF({$prefix}.{$sqlFieldName} is not null, 1, 0) as {$sqlFieldName}";
  378. default: return "{$prefix}.{$sqlFieldName}";
  379. }
  380. }
  381. // 'gml:PolygonPropertyType':
  382. // 'gml:PointPropertyType':
  383. // 'gml:LineStringPropertyType':
  384. // 'gml:GeometryPropertyType':
  385. case 'gml': return "AsWKT({$prefix}.{$sqlFieldName}) as {$sqlFieldName}";
  386. case 'p5': {
  387. switch ($typeName) {
  388. case 'text': return "{$prefix}.{$sqlFieldName}";
  389. case 'price': return "{$prefix}.{$sqlFieldName}";
  390. case 'enum': return "{$prefix}.{$sqlFieldName}"; // TODO: check if local or remote
  391. case 'www_link': return "{$prefix}.{$sqlFieldName}"; // TODO: check if local or remote?
  392. case 'string': return "{$prefix}.{$sqlFieldName}"; // TODO: check if local or remote?
  393. default: throw new Exception("Not implemented field type in select '{$fieldType}' (field: '{$fieldName}')");
  394. }
  395. }
  396. case 'p5Type': {
  397. // g 'p5Type:' SE/schema/ant-object/|awk -F'p5Type:' '{print $2}'|awk -F'"' '{print $1}'|sort -u
  398. // result at @2018-04-17:
  399. // date
  400. // dateTime
  401. // decimal
  402. // integer
  403. // lineString
  404. // point
  405. // polygon
  406. // string
  407. // text
  408. switch ($typeName) {
  409. case 'text': return "{$prefix}.{$sqlFieldName}";
  410. case 'price': return "{$prefix}.{$sqlFieldName}";
  411. case 'enum': return "{$prefix}.{$sqlFieldName}"; // TODO: check if local or remote
  412. case 'www_link': return "{$prefix}.{$sqlFieldName}"; // TODO: check if local or remote?
  413. case 'string': return "{$prefix}.{$sqlFieldName}"; // TODO: check if local or remote?
  414. case 'date':
  415. case 'dateTime':
  416. case 'decimal':
  417. case 'double':
  418. case 'float':
  419. case 'hexBinary':
  420. case 'text':
  421. case 'time':
  422. case 'year':
  423. case 'integer': return "{$prefix}.{$sqlFieldName}"; // TODO: check if local or remote?
  424. case 'polygon':
  425. case 'lineString':
  426. case 'point': return "AsWKT({$prefix}.{$sqlFieldName}) as {$sqlFieldName}";
  427. default: throw new Exception("Not implemented field type in select '{$fieldType}' (field: '{$fieldName}')");
  428. }
  429. }
  430. default: throw new Exception("Not implemented field type in select '{$fieldType}' (field: '{$fieldName}')");
  431. }
  432. return null;
  433. }
  434. }