AclQueryBuilder.php 15 KB

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