AclQueryBuilder.php 15 KB

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