AclQueryBuilder.php 16 KB

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