AclQueryBuilder.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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 $isInstances;
  28. public $isNotInstances;
  29. public $_hasSelectRemoteFields;
  30. public $_hasQueryRemoteFields;
  31. public function __construct() {
  32. $this->select = [];
  33. $this->from = null; // (ACL | tableName)
  34. $this->where = [];
  35. $this->orderBy = null;
  36. $this->groupBy = null;
  37. $this->limit = null;
  38. $this->offset = null;
  39. $this->_fromPrefix = 't'; // prefix for this->from - default 't'
  40. $this->_joinPrefix = []; // prefix => from (Acl | tableName)
  41. $this->_joinParams = []; // prefx => params
  42. $this->isInstances = [];
  43. $this->isNotInstances = [];
  44. $this->_hasSelectRemoteFields = false;
  45. $this->_hasQueryRemoteFields = false;
  46. }
  47. public function from($from, $prefix = 't') {
  48. DBG::log([
  49. 'from instanceof Core_AclBase' => ($from instanceof Core_AclBase),
  50. 'from instanceof AntAclBase' => ($from instanceof AntAclBase),
  51. 'from instanceof TableAcl' => ($from instanceof TableAcl),
  52. ], 'array', "\$from class(".get_class($from).")");
  53. if ($this->from) throw new Exception("Duplicate FROM");
  54. $this->from = $from;
  55. $this->_fromPrefix = $prefix;
  56. return $this;
  57. }
  58. public function select($propertyName) { // TODO: ogc:propertyName, *, xpath, @instances, etc...
  59. if (empty($propertyName)) return $this; // SKIP empty values, null's, etc.
  60. DBG::log($propertyName, 'array', "AclQueryBuilder->select");
  61. if (is_array($propertyName)) {
  62. $hasWildcard = in_array('*', $propertyName);
  63. foreach ($propertyName as $k => $v) {
  64. if ('rawSelect' === $k) $this->select['__rawSelect__'] = $v;
  65. else if ('*' === $v) continue;
  66. else $this->select[] = $v;
  67. }
  68. if ($hasWildcard) array_unshift($this->select, '*');
  69. return $this;
  70. }
  71. if (!in_array($propertyName, $this->select)) $this->select[] = $propertyName; // TODO: split by property source
  72. return $this;
  73. }
  74. public function where($where) {
  75. if (null === $where) return $this;
  76. if (is_string($where)) return $this->whereRaw($where);
  77. list($fieldName, $comparisonSign, $value) = $where;
  78. if (!in_array($comparisonSign, [ // validation
  79. '=', '<', '>', '<=', '>=', '<>', '!='
  80. , 'like', 'not like'
  81. , 'is not null', 'is null'
  82. , 'Intersects', 'GeometryType'
  83. , 'or' // $value = [ comparisons for $fieldName ... or null ]
  84. , 'and' // $value = [ comparisons for $fieldName ... or null ]
  85. ])) {
  86. throw new Exception("Not implemented comparisonSign '{$comparisonSign}'");
  87. }
  88. $this->where[] = [$fieldName, $comparisonSign, $value];
  89. return $this;
  90. }
  91. public function _generateWhereMain($where) { // @returns string
  92. if (is_string($where)) return $where; // whereRaw
  93. list($fieldName, $comparisonSign, $value) = $where;
  94. $sqlFieldName = $fieldName; // TODO: getSqlFieldName // TODO: get sql field name with table prefix from join list to replace "{$this->_fromPrefix}.{$sqlFieldName}" below
  95. switch ($comparisonSign) {
  96. case 'is not null': return "{$this->_fromPrefix}.{$sqlFieldName} is not null";
  97. case 'is null': return "{$this->_fromPrefix}.{$sqlFieldName} is null";
  98. case 'Intersects': return "Intersects(GeomFromText('{$value}'), {$this->_fromPrefix}.`{$sqlFieldName}`)=1";
  99. case 'GeometryType': return "GeometryType({$this->_fromPrefix}.`{$sqlFieldName}`)='{$value}'";
  100. case 'or': return $this->_generateWhereBlock($where);
  101. case 'and': return $this->_generateWhereBlock($where);
  102. case 'UNIX_TIMESTAMP_LESS_THAN_NOW': return "
  103. COALESCE(UNIX_TIMESTAMP({$this->_fromPrefix}.`{$sqlFieldName}`), 0) < UNIX_TIMESTAMP()
  104. and {$this->_fromPrefix}.`{$sqlFieldName}` != ''
  105. and {$this->_fromPrefix}.`{$sqlFieldName}` != '0000-00-00 00:00:00'
  106. ";
  107. case 'UNIX_TIMESTAMP_NOW_3600': return "
  108. COALESCE(UNIX_TIMESTAMP({$this->_fromPrefix}.`{$sqlFieldName}`), 0) < UNIX_TIMESTAMP()+3600
  109. and COALESCE(UNIX_TIMESTAMP({$this->_fromPrefix}.`{$sqlFieldName}`), 0) > UNIX_TIMESTAMP()-3600
  110. ";
  111. case 'UNIX_TIMESTAMP_GREATER_THAN': return " COALESCE(UNIX_TIMESTAMP({$this->_fromPrefix}.`{$sqlFieldName}`), 0) > '{$value}' ";
  112. case 'UNIX_TIMESTAMP_LESS_THAN': return " COALESCE(UNIX_TIMESTAMP({$this->_fromPrefix}.`{$sqlFieldName}`), 0) < '{$value}' ";
  113. default: return "{$this->_fromPrefix}.{$sqlFieldName} {$comparisonSign} " . DB::getPDO()->quote($value);
  114. }
  115. return null;
  116. }
  117. public function _generateWhereBlock($where) { // @returns string
  118. list($fieldName, $sqlGlue, $list) = $where;
  119. $list = array_filter($list, function ($value) { return null !== $value; });
  120. $sqlList = array_filter(
  121. array_map([$this, '_generateWhereMain'], $list),
  122. 'is_string'
  123. );
  124. if (1 === count($sqlList)) return $sqlList[0];
  125. else return "( " . implode(" {$sqlGlue} ", $sqlList) . " )";
  126. }
  127. public function whereIsNotNull($fieldName) {
  128. $this->where[] = "{$this->_fromPrefix}.{$fieldName} is not null";
  129. return $this;
  130. }
  131. public function whereRaw($rawWhere) { // add where without validation
  132. if (!$rawWhere) return $this;
  133. $this->where[] = $rawWhere;
  134. return $this;
  135. }
  136. // public function whereFunction($column, $operator = null, $value = null) {
  137. public function whereFunction($fieldName, $comparisonSign = null, $value = null) {
  138. throw new Exception("whereFunction not supported");
  139. $this->where[] = '';
  140. return $this;
  141. }
  142. public function generateWhereSql() { // @return string - sql without where keyword
  143. $sqlWhere = array_filter(
  144. array_map([$this, '_generateWhereMain'], $this->where),
  145. 'is_string'
  146. );
  147. return (!empty($sqlWhere)) ? implode("\n\t and ", $sqlWhere) : '';
  148. }
  149. public function _generateSelectMain($select, $key) {
  150. if ('__rawSelect__' === $key) return $select;
  151. $sqlPk = 'ID';
  152. if ($this->from instanceof Core_AclBase) $sqlPk = $this->from->getSqlPrimaryKeyField();
  153. if ('*' === $select) return "{$this->_fromPrefix}.*";
  154. if ('@instances' === $select) {
  155. if (!($this->from instanceof Core_AclBase)) throw new Exception("select @instances allowed only for Acl object");
  156. $instanceTable = ACL::getInstanceTable($this->from->getNamespace());
  157. return "
  158. (
  159. select GROUP_CONCAT(inst_conf.namespace)
  160. from `{$instanceTable}` inst_tbl
  161. join `CRM_INSTANCE_CONFIG` inst_conf on (inst_conf.id = inst_tbl.idInstance)
  162. where inst_tbl.pk = {$this->_fromPrefix}.{$sqlPk}
  163. ) as `@instances`
  164. ";
  165. }
  166. if (is_array($select)) {
  167. // TODO: [ '__backRef' => [ ... ] ]
  168. DBG::log($select, 'array', "TODO: select array");
  169. return null;
  170. }
  171. if (is_string($select)) {
  172. // TODO: only real table field
  173. // TODO: if geometry type then `AsWKT(t.`{$fieldName}`) as {$fieldName}`
  174. try {
  175. return $this->parseSelectFieldValueToSql($select, $this->_fromPrefix);
  176. } catch (Exception $e) {
  177. DBG::log($e);
  178. }
  179. }
  180. return null;
  181. }
  182. public function join($join, $prefix, $params) {
  183. if (array_key_exists($prefix, $this->_joinPrefix)) throw new Exception("Prefix already used!");
  184. $this->_joinPrefix[$prefix] = $join;
  185. $this->_joinParams[$prefix] = $params;
  186. return $this;
  187. }
  188. public function orderBy($orderBy) { // TODO: ogc: order by ...
  189. if (null !== $this->orderBy) throw new Exception("OrderBy already set!");
  190. $this->orderBy = [];
  191. if (!$orderBy) return $this;
  192. // ID A,COL_X D,COL_Y A,...
  193. if (false !== strpos($orderBy, '+')) $orderBy = str_replace('+', ' ', $orderBy);
  194. $sortByEx = array_map('trim', explode(',', $orderBy));
  195. $sortByEx = array_filter($sortByEx, ['V', 'filterNotEmpty']);
  196. foreach ($sortByEx as $sortPart) {
  197. $sortPartEx = explode(' ', $sortPart);
  198. if (count($sortPartEx) > 2) throw new Exception("SortBy parse error #" . __LINE__);
  199. $fieldName = trim($sortPartEx[0]);
  200. if (!$this->isFieldAllowedToOrderBy($fieldName)) throw new Exception("SortBy parse error for field '{$fieldName}' #" . __LINE__);
  201. $colSortDir = 'ASC';
  202. if (count($sortPartEx) == 2) {
  203. if ('A' == strtoupper($sortPartEx[1]) || 'ASC' == strtoupper($sortPartEx[1])) {
  204. } else if ('D' == strtoupper($sortPartEx[1]) || 'DESC' == strtoupper($sortPartEx[1])) {
  205. $colSortDir = 'DESC';
  206. } else throw new Exception("SortBy parse error - unknown sort order '{$sortPartEx[1]}' #" . __LINE__);
  207. }
  208. $this->orderBy[] = [$fieldName, $colSortDir];
  209. DBG::log($this->orderBy, 'array', "sortBy");
  210. }
  211. return $this;
  212. }
  213. public function isFieldAllowedToOrderBy($fieldName) {
  214. return true; // TODO:? only local fields in $this->from
  215. }
  216. public function generateOrderBySql() {
  217. if (empty($this->orderBy)) return '';
  218. $sortByList = [];
  219. foreach ($this->orderBy as $orderBy) {
  220. $sortByList[] = "t.`{$orderBy[0]}` {$orderBy[1]}";
  221. }
  222. return (!empty($sortByList))
  223. ? "order by " . implode(", ", $sortByList)
  224. : '';
  225. }
  226. public function limit($limit) {
  227. $this->limit = (int)$limit;
  228. return $this;
  229. }
  230. public function offset($offset) {
  231. $this->offset = (int)$offset;
  232. return $this;
  233. }
  234. public function isInstance($instances) {
  235. $this->isInstances = (is_array($instances)) ? $instances : [ $instances ];
  236. return $this;
  237. }
  238. public function isNotInstance($instances) {
  239. $this->isNotInstances = (is_array($instances)) ? $instances : [ $instances ];
  240. return $this;
  241. }
  242. public function _parseJoinParams($params) {
  243. if (array_key_exists('rawJoin', $params)) return $params['rawJoin'];
  244. throw new Exception("Not implemented JOIN params '".json_encode($params)."'");
  245. }
  246. public function _getTableName($source) {
  247. if (is_scalar($source)) return $source;
  248. if ($source instanceof Core_AclBase) return $source->getRootTableName();
  249. throw new Exception("Not implemented FROM type '".get_class($source)."'");
  250. }
  251. public function execute() {
  252. return $this->fetchAll();
  253. }
  254. public function fetchAll() {
  255. $sql = $this->generateSql();
  256. DBG::log((array)$this, 'array', "AclQueryBuilder::fetchAll");
  257. return DB::getPDO()->fetchAll($sql);
  258. }
  259. public function fetchTotal() {
  260. $sql = $this->generateSql("count(*) as cnt");
  261. return DB::getPDO()->fetchValue($sql);
  262. }
  263. public function fetchValue() {
  264. $sql = $this->generateSql();
  265. DBG::log(['sql'=>$sql,'this'=>(array)$this], 'array', "AclQueryBuilder::fetchValue");
  266. return DB::getPDO()->fetchValue($sql);
  267. }
  268. public function fetchFirst() {
  269. $sql = $this->generateSql();
  270. DBG::log(['sql'=>$sql,'this'=>(array)$this], 'array', "AclQueryBuilder::fetchFirst");
  271. return DB::getPDO()->fetchFirst($sql);
  272. }
  273. public function generateSql($select = null) {
  274. if (!$this->from) throw new Exception("Missing FROM");
  275. $tableName = $this->_getTableName($this->from);
  276. if (!$tableName) throw new Exception("Missing FROM table name");
  277. $sqlPk = ($this->from instanceof Core_AclBase)
  278. ? $this->from->getSqlPrimaryKeyField()
  279. : 'ID';
  280. $sqlJoin = [];
  281. DBG::log($this, 'array', '$this');
  282. foreach ($this->isInstances as $k => $ns) {
  283. $idInstance = ACL::getInstanceId($ns);
  284. $instanceTable = ACL::getInstanceTable($ns);
  285. // ->join($instanceTable, 'i', [ 'rawJoin' => "i.pk = t.{$sqlPk} and i.idInstance = {$idInstance}" ])
  286. $prefix = "is_inst_{$k}";
  287. // $sqlJoin[] = " inner join `{$joinName}` {$prefix} on (
  288. // {$prefix}.pk = {$this->_fromPrefix}.{$sqlPk}
  289. // and {$prefix}.idInstance = {$idInstance}
  290. // )";
  291. $this->where[] = "{$this->_fromPrefix}.{$sqlPk} in (
  292. select {$prefix}.pk
  293. from `{$instanceTable}` {$prefix}
  294. where {$prefix}.idInstance = {$idInstance}
  295. )";
  296. DBG::log("{$this->_fromPrefix}.{$sqlPk} in (
  297. select {$prefix}.pk
  298. from `{$instanceTable}` {$prefix}
  299. where {$prefix}.idInstance = {$idInstance}
  300. )", 'string', "\$this->where[] =");
  301. }
  302. foreach ($this->isNotInstances as $k => $ns) {
  303. $idInstance = ACL::getInstanceId($ns);
  304. $instanceTable = ACL::getInstanceTable($ns);
  305. // ->join($instanceTable, 'i', [ 'rawJoin' => "i.pk = t.{$sqlPk} and i.idInstance = {$idInstance}" ])
  306. $prefix = "is_inst_{$k}";
  307. // $sqlJoin[] = " inner join `{$joinName}` {$prefix} on (
  308. // {$prefix}.pk = {$this->_fromPrefix}.{$sqlPk}
  309. // and {$prefix}.idInstance = {$idInstance}
  310. // )";
  311. $this->where[] = "{$this->_fromPrefix}.{$sqlPk} not in (
  312. select {$prefix}.pk
  313. from `{$instanceTable}` {$prefix}
  314. where {$prefix}.idInstance = {$idInstance}
  315. )";
  316. }
  317. // join `{$instanceTable}` i on(i.pk = t.{$sqlPk} and i.idInstance = {$idInstance})
  318. foreach ($this->_joinPrefix as $prefix => $join) {
  319. $joinName = $this->_getTableName($join);
  320. $sqlJoin[] = " join `{$joinName}` {$prefix} on(" . $this->_parseJoinParams($this->_joinParams[$prefix]) . ")";
  321. }
  322. $sqlJoin = (!empty($sqlJoin)) ? implode("\n\t", $sqlJoin) : "";
  323. DBG::log($this->where, 'array', "generateSql \$this->where");
  324. $sqlWhere = array_filter(
  325. array_map([$this, '_generateWhereMain'], $this->where),
  326. 'is_string'
  327. );
  328. $sqlWhere = (!empty($sqlWhere)) ? "where " . implode("\n\t and ", $sqlWhere) : '';
  329. $limit = ($this->limit < 0) ? 0 : $this->limit;
  330. $offset = ($this->offset < 0) ? 0 : $this->offset;
  331. $sqlLimit = ($limit > 0) ? "limit {$limit} offset {$offset}" : '';
  332. // TODO: split select to local and remote (use field isLocal)
  333. // TODO: $this->_hasSelectRemoteFields = false;
  334. // TODO: $this->_hasQueryRemoteFields = false;
  335. if ($select) {
  336. $sqlSelect = $select; // used for example fetchTotal -> generateSql("count(*) as cnt")
  337. } else {
  338. $sqlSelect = array_filter(
  339. array_map([$this, '_generateSelectMain'], $this->select, array_keys($this->select)),
  340. 'is_string'
  341. );
  342. $sqlSelect = (!empty($sqlSelect))
  343. ? implode(",\n\t", $sqlSelect)
  344. : "{$this->_fromPrefix}.*"
  345. ;
  346. }
  347. $sqlOrderBy = $this->generateOrderBySql();
  348. return "
  349. select {$sqlSelect}
  350. from `{$tableName}` {$this->_fromPrefix}
  351. {$sqlJoin}
  352. {$sqlWhere}
  353. {$sqlOrderBy}
  354. {$sqlLimit}
  355. ";
  356. }
  357. public function parseSelectFieldValueToSql($fieldName, $prefix = 't') {
  358. if (false !== strpos($fieldName, '/')) {
  359. DBG::log($fieldName, 'string', "TODO: select by xpath");
  360. throw new Exception("Not implemented select by xpath ('{$fieldName}')");
  361. }
  362. $fieldType = $this->from->getXsdFieldType($fieldName);
  363. @list($typePrefix, $typeName, $retTypeName) = explode(':', $fieldType);
  364. switch ($typePrefix) {
  365. case 'xsd': return "{$prefix}.`{$fieldName}`";
  366. // 'gml:PolygonPropertyType':
  367. // 'gml:PointPropertyType':
  368. // 'gml:LineStringPropertyType':
  369. // 'gml:GeometryPropertyType':
  370. case 'gml': return "AsWKT({$prefix}.`{$fieldName}`) as `{$fieldName}`";
  371. case 'p5': {
  372. switch ($typeName) {
  373. case 'price': return "{$prefix}.`{$fieldName}`";
  374. case 'enum': return "{$prefix}.`{$fieldName}`"; // TODO: check if local or remote
  375. case 'www_link': return "{$prefix}.`{$fieldName}`"; // TODO: check if local or remote?
  376. case 'string': return "{$prefix}.`{$fieldName}`"; // TODO: check if local or remote?
  377. default: throw new Exception("Not implemented field type in select '{$fieldType}' (field: '{$fieldName}')");
  378. }
  379. }
  380. default: throw new Exception("Not implemented field type in select '{$fieldType}' (field: '{$fieldName}')");
  381. }
  382. return null;
  383. }
  384. }