AclQueryBuilder.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. $sortByEx = array_map('trim', explode(',', $orderBy));
  194. $sortByEx = array_filter($sortByEx, ['V', 'filterNotEmpty']);
  195. foreach ($sortByEx as $sortPart) {
  196. $sortPartEx = explode(' ', $sortPart);
  197. if (count($sortPartEx) > 2) throw new Exception("SortBy parse error #" . __LINE__);
  198. $fieldName = trim($sortPartEx[0]);
  199. if (!$this->isFieldAllowedToOrderBy($fieldName)) throw new Exception("SortBy parse error for field '{$fieldName}' #" . __LINE__);
  200. $colSortDir = 'ASC';
  201. if (count($sortPartEx) == 2) {
  202. if ('A' == strtoupper($sortPartEx[1]) || 'ASC' == strtoupper($sortPartEx[1])) {
  203. } else if ('D' == strtoupper($sortPartEx[1]) || 'DESC' == strtoupper($sortPartEx[1])) {
  204. $colSortDir = 'DESC';
  205. } else throw new Exception("SortBy parse error - unknown sort order '{$sortPartEx[1]}' #" . __LINE__);
  206. }
  207. $this->orderBy[] = [$fieldName, $colSortDir];
  208. DBG::log($this->orderBy, 'array', "sortBy");
  209. }
  210. return $this;
  211. }
  212. public function isFieldAllowedToOrderBy($fieldName) {
  213. return true;
  214. }
  215. public function generateOrderBySql() {
  216. if (empty($this->orderBy)) return '';
  217. $sortByList = [];
  218. foreach ($this->orderBy as $orderBy) {
  219. $sortByList[] = "t.`{$orderBy[0]}` {$orderBy[1]}";
  220. }
  221. return (!empty($sortByList))
  222. ? "order by " . implode(", ", $sortByList)
  223. : '';
  224. }
  225. public function limit($limit) {
  226. $this->limit = (int)$limit;
  227. return $this;
  228. }
  229. public function offset($offset) {
  230. $this->offset = (int)$offset;
  231. return $this;
  232. }
  233. public function isInstance($instances) {
  234. $this->isInstances = (is_array($instances)) ? $instances : [ $instances ];
  235. return $this;
  236. }
  237. public function isNotInstance($instances) {
  238. $this->isNotInstances = (is_array($instances)) ? $instances : [ $instances ];
  239. return $this;
  240. }
  241. public function _parseJoinParams($params) {
  242. if (array_key_exists('rawJoin', $params)) return $params['rawJoin'];
  243. throw new Exception("Not implemented JOIN params '".json_encode($params)."'");
  244. }
  245. public function _getTableName($source) {
  246. if (is_scalar($source)) return $source;
  247. if ($source instanceof Core_AclBase) return $source->getRootTableName();
  248. throw new Exception("Not implemented FROM type '".get_class($source)."'");
  249. }
  250. public function execute() {
  251. return $this->fetchAll();
  252. }
  253. public function fetchAll() {
  254. $sql = $this->generateSql();
  255. DBG::log((array)$this, 'array', "AclQueryBuilder::fetchAll");
  256. return DB::getPDO()->fetchAll($sql);
  257. }
  258. public function fetchTotal() {
  259. $sql = $this->generateSql("count(*) as cnt");
  260. return DB::getPDO()->fetchValue($sql);
  261. }
  262. public function fetchValue() {
  263. $sql = $this->generateSql();
  264. DBG::log(['sql'=>$sql,'this'=>(array)$this], 'array', "AclQueryBuilder::fetchValue");
  265. return DB::getPDO()->fetchValue($sql);
  266. }
  267. public function fetchFirst() {
  268. $sql = $this->generateSql();
  269. DBG::log(['sql'=>$sql,'this'=>(array)$this], 'array', "AclQueryBuilder::fetchFirst");
  270. return DB::getPDO()->fetchFirst($sql);
  271. }
  272. public function generateSql($select = null) {
  273. if (!$this->from) throw new Exception("Missing FROM");
  274. $tableName = $this->_getTableName($this->from);
  275. if (!$tableName) throw new Exception("Missing FROM table name");
  276. $sqlPk = ($this->from instanceof Core_AclBase)
  277. ? $this->from->getSqlPrimaryKeyField()
  278. : 'ID';
  279. $sqlJoin = [];
  280. DBG::log($this, 'array', '$this');
  281. foreach ($this->isInstances as $k => $ns) {
  282. $idInstance = ACL::getInstanceId($ns);
  283. $instanceTable = ACL::getInstanceTable($ns);
  284. // ->join($instanceTable, 'i', [ 'rawJoin' => "i.pk = t.{$sqlPk} and i.idInstance = {$idInstance}" ])
  285. $prefix = "is_inst_{$k}";
  286. // $sqlJoin[] = " inner join `{$joinName}` {$prefix} on (
  287. // {$prefix}.pk = {$this->_fromPrefix}.{$sqlPk}
  288. // and {$prefix}.idInstance = {$idInstance}
  289. // )";
  290. $this->where[] = "{$this->_fromPrefix}.{$sqlPk} in (
  291. select {$prefix}.pk
  292. from `{$instanceTable}` {$prefix}
  293. where {$prefix}.idInstance = {$idInstance}
  294. )";
  295. DBG::log("{$this->_fromPrefix}.{$sqlPk} in (
  296. select {$prefix}.pk
  297. from `{$instanceTable}` {$prefix}
  298. where {$prefix}.idInstance = {$idInstance}
  299. )", 'string', "\$this->where[] =");
  300. }
  301. foreach ($this->isNotInstances as $k => $ns) {
  302. $idInstance = ACL::getInstanceId($ns);
  303. $instanceTable = ACL::getInstanceTable($ns);
  304. // ->join($instanceTable, 'i', [ 'rawJoin' => "i.pk = t.{$sqlPk} and i.idInstance = {$idInstance}" ])
  305. $prefix = "is_inst_{$k}";
  306. // $sqlJoin[] = " inner join `{$joinName}` {$prefix} on (
  307. // {$prefix}.pk = {$this->_fromPrefix}.{$sqlPk}
  308. // and {$prefix}.idInstance = {$idInstance}
  309. // )";
  310. $this->where[] = "{$this->_fromPrefix}.{$sqlPk} not in (
  311. select {$prefix}.pk
  312. from `{$instanceTable}` {$prefix}
  313. where {$prefix}.idInstance = {$idInstance}
  314. )";
  315. }
  316. // join `{$instanceTable}` i on(i.pk = t.{$sqlPk} and i.idInstance = {$idInstance})
  317. foreach ($this->_joinPrefix as $prefix => $join) {
  318. $joinName = $this->_getTableName($join);
  319. $sqlJoin[] = " join `{$joinName}` {$prefix} on(" . $this->_parseJoinParams($this->_joinParams[$prefix]) . ")";
  320. }
  321. $sqlJoin = (!empty($sqlJoin)) ? implode("\n\t", $sqlJoin) : "";
  322. DBG::log($this->where, 'array', "generateSql \$this->where");
  323. $sqlWhere = array_filter(
  324. array_map([$this, '_generateWhereMain'], $this->where),
  325. 'is_string'
  326. );
  327. $sqlWhere = (!empty($sqlWhere)) ? "where " . implode("\n\t and ", $sqlWhere) : '';
  328. $limit = ($this->limit < 0) ? 0 : $this->limit;
  329. $offset = ($this->offset < 0) ? 0 : $this->offset;
  330. $sqlLimit = ($limit > 0) ? "limit {$limit} offset {$offset}" : '';
  331. // TODO: split select to local and remote (use field isLocal)
  332. // TODO: $this->_hasSelectRemoteFields = false;
  333. // TODO: $this->_hasQueryRemoteFields = false;
  334. if ($select) {
  335. $sqlSelect = $select; // used for example fetchTotal -> generateSql("count(*) as cnt")
  336. } else {
  337. $sqlSelect = array_filter(
  338. array_map([$this, '_generateSelectMain'], $this->select, array_keys($this->select)),
  339. 'is_string'
  340. );
  341. $sqlSelect = (!empty($sqlSelect))
  342. ? implode(",\n\t", $sqlSelect)
  343. : "{$this->_fromPrefix}.*"
  344. ;
  345. }
  346. $sqlOrderBy = $this->generateOrderBySql();
  347. return "
  348. select {$sqlSelect}
  349. from `{$tableName}` {$this->_fromPrefix}
  350. {$sqlJoin}
  351. {$sqlWhere}
  352. {$sqlOrderBy}
  353. {$sqlLimit}
  354. ";
  355. }
  356. public function parseSelectFieldValueToSql($fieldName, $prefix = 't') {
  357. if (false !== strpos($fieldName, '/')) {
  358. DBG::log($fieldName, 'string', "TODO: select by xpath");
  359. throw new Exception("Not implemented select by xpath ('{$fieldName}')");
  360. }
  361. $fieldType = $this->from->getXsdFieldType($fieldName);
  362. @list($typePrefix, $typeName, $retTypeName) = explode(':', $fieldType);
  363. switch ($typePrefix) {
  364. case 'xsd': return "{$prefix}.`{$fieldName}`";
  365. // 'gml:PolygonPropertyType':
  366. // 'gml:PointPropertyType':
  367. // 'gml:LineStringPropertyType':
  368. // 'gml:GeometryPropertyType':
  369. case 'gml': return "AsWKT({$prefix}.`{$fieldName}`) as `{$fieldName}`";
  370. case 'p5': {
  371. switch ($typeName) {
  372. case 'price': return "{$prefix}.`{$fieldName}`";
  373. case 'enum': return "{$prefix}.`{$fieldName}`"; // TODO: check if local or remote
  374. case 'www_link': return "{$prefix}.`{$fieldName}`"; // TODO: check if local or remote?
  375. default: throw new Exception("Not implemented field type in select '{$fieldType}' (field: '{$fieldName}')");
  376. }
  377. }
  378. default: throw new Exception("Not implemented field type in select '{$fieldType}' (field: '{$fieldName}')");
  379. }
  380. return null;
  381. }
  382. }