AclQueryBuilder.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 _generateSelectMain($select, $key) {
  137. if ('__rawSelect__' === $key) return $select;
  138. $sqlPk = 'ID';
  139. if ($this->from instanceof Core_AclBase) $sqlPk = $this->from->getSqlPrimaryKeyField();
  140. if ('@instnces' === $select) {
  141. if (!($this->from instanceof Core_AclBase)) throw new Exception("select @instances allowed only for Acl object");
  142. $instanceTable = ACL::getInstanceTable($this->from->getNamespace());
  143. return "
  144. (
  145. select GROUP_CONCAT(inst_conf.namespace)
  146. from `{$instanceTable}` inst_tbl
  147. join `CRM_INSTANCE_CONFIG` inst_conf on (inst_conf.id = inst_tbl.idInstance)
  148. where inst_tbl.pk = {$this->_fromPrefix}.{$sqlPk}
  149. ) as `@instances`
  150. ";
  151. }
  152. if (is_array($select)) {
  153. // TODO: [ '__backRef' => [ ... ] ]
  154. DBG::log($select, 'array', "TODO: select array");
  155. } else {
  156. // TODO: only real table field
  157. // TODO: if geometry type then `AsWKT(t.`{$fieldName}`) as {$fieldName}`
  158. return $this->parseSelectFieldValueToSql($select, $this->_fromPrefix);
  159. }
  160. return null;
  161. }
  162. public function join($join, $prefix, $params) {
  163. if (array_key_exists($prefix, $this->_joinPrefix)) throw new Exception("Prefix already used!");
  164. $this->_joinPrefix[$prefix] = $join;
  165. $this->_joinParams[$prefix] = $params;
  166. return $this;
  167. }
  168. public function orderBy($orderBy) { // TODO: ogc: order by ...
  169. if (null !== $this->orderBy) throw new Exception("OrderBy already set!");
  170. $this->orderBy = [];
  171. if (!$orderBy) return $this;
  172. // ID A,COL_X D,COL_Y A,...
  173. $sortByEx = array_map('trim', explode(',', $orderBy));
  174. $sortByEx = array_filter($sortByEx, function ($part) { return !empty($part); });
  175. foreach ($sortByEx as $sortPart) {
  176. $sortPartEx = explode(' ', $sortPart);
  177. if (count($sortPartEx) > 2) throw new Exception("SortBy parse error #" . __LINE__);
  178. $fieldName = trim($sortPartEx[0]);
  179. if (!$this->isFieldAllowedToOrderBy($fieldName)) throw new Exception("SortBy parse error for field '{$fieldName}' #" . __LINE__);
  180. $colSortDir = 'ASC';
  181. if (count($sortPartEx) == 2) {
  182. if ('A' == strtoupper($sortPartEx[1]) || 'ASC' == strtoupper($sortPartEx[1])) {
  183. } else if ('D' == strtoupper($sortPartEx[1]) || 'DESC' == strtoupper($sortPartEx[1])) {
  184. $colSortDir = 'DESC';
  185. } else throw new Exception("SortBy parse error - unknown sort order '{$sortPartEx[1]}' #" . __LINE__);
  186. }
  187. $this->orderBy[] = [$fieldName, $colSortDir];
  188. }
  189. return $this;
  190. }
  191. public function isFieldAllowedToOrderBy($fieldName) {
  192. return true;
  193. }
  194. public function generateOrderBySql() {
  195. if (empty($this->orderBy)) return '';
  196. $sortByList = [];
  197. foreach ($this->orderBy as $orderBy) {
  198. $sortByList[] = "t.`{$orderBy[0]}` {$orderBy[1]}";
  199. }
  200. return (!empty($sortByList))
  201. ? "order by " . implode(", ", $sortByList)
  202. : '';
  203. }
  204. public function limit($limit) {
  205. $this->limit = (int)$limit;
  206. return $this;
  207. }
  208. public function offset($offset) {
  209. $this->offset = (int)$offset;
  210. return $this;
  211. }
  212. public function isInstance($instances) {
  213. $this->isInstances = (is_array($instances)) ? $instances : [ $instances ];
  214. return $this;
  215. }
  216. public function isNotInstance($instances) {
  217. $this->isNotInstances = (is_array($instances)) ? $instances : [ $instances ];
  218. return $this;
  219. }
  220. public function _parseJoinParams($params) {
  221. if (array_key_exists('rawJoin', $params)) return $params['rawJoin'];
  222. throw new Exception("Not implemented JOIN params '".json_encode($params)."'");
  223. }
  224. public function _getTableName($source) {
  225. if (is_scalar($source)) return $source;
  226. if ($source instanceof Core_AclBase) return $source->getRootTableName();
  227. throw new Exception("Not implemented FROM type '".get_class($source)."'");
  228. }
  229. public function execute() {
  230. return $this->fetchAll();
  231. }
  232. public function fetchAll() {
  233. $sql = $this->generateSql();
  234. DBG::log((array)$this, 'array', "AclQueryBuilder::fetchAll");
  235. return DB::getPDO()->fetchAll($sql);
  236. }
  237. public function fetchValue() {
  238. $sql = $this->generateSql();
  239. DBG::log(['sql'=>$sql,'this'=>(array)$this], 'array', "AclQueryBuilder::fetchValue");
  240. return DB::getPDO()->fetchValue($sql);
  241. }
  242. public function generateSql() {
  243. if (!$this->from) throw new Exception("Missing FROM");
  244. $tableName = $this->_getTableName($this->from);
  245. if (!$tableName) throw new Exception("Missing FROM table name");
  246. $sqlPk = 'ID';
  247. if ($this->from instanceof Core_AclBase) $sqlPk = $this->from->getSqlPrimaryKeyField();
  248. $sqlJoin = [];
  249. DBG::log($this, 'array', '$this');
  250. foreach ($this->isInstances as $k => $ns) {
  251. $idInstance = ACL::getInstanceId($ns);
  252. $instanceTable = ACL::getInstanceTable($ns);
  253. // ->join($instanceTable, 'i', [ 'rawJoin' => "i.pk = t.{$sqlPk} and i.idInstance = {$idInstance}" ])
  254. $prefix = "is_inst_{$k}";
  255. // $sqlJoin[] = " inner join `{$joinName}` {$prefix} on (
  256. // {$prefix}.pk = {$this->_fromPrefix}.{$sqlPk}
  257. // and {$prefix}.idInstance = {$idInstance}
  258. // )";
  259. $this->where[] = "{$this->_fromPrefix}.{$sqlPk} in (
  260. select {$prefix}.pk
  261. from `{$instanceTable}` {$prefix}
  262. where {$prefix}.idInstance = {$idInstance}
  263. )";
  264. DBG::log("{$this->_fromPrefix}.{$sqlPk} in (
  265. select {$prefix}.pk
  266. from `{$instanceTable}` {$prefix}
  267. where {$prefix}.idInstance = {$idInstance}
  268. )", 'string', "\$this->where[] =");
  269. }
  270. foreach ($this->isNotInstances as $k => $ns) {
  271. $idInstance = ACL::getInstanceId($ns);
  272. $instanceTable = ACL::getInstanceTable($ns);
  273. // ->join($instanceTable, 'i', [ 'rawJoin' => "i.pk = t.{$sqlPk} and i.idInstance = {$idInstance}" ])
  274. $prefix = "is_inst_{$k}";
  275. // $sqlJoin[] = " inner join `{$joinName}` {$prefix} on (
  276. // {$prefix}.pk = {$this->_fromPrefix}.{$sqlPk}
  277. // and {$prefix}.idInstance = {$idInstance}
  278. // )";
  279. $this->where[] = "{$this->_fromPrefix}.{$sqlPk} not in (
  280. select {$prefix}.pk
  281. from `{$instanceTable}` {$prefix}
  282. where {$prefix}.idInstance = {$idInstance}
  283. )";
  284. }
  285. // join `{$instanceTable}` i on(i.pk = t.{$sqlPk} and i.idInstance = {$idInstance})
  286. foreach ($this->_joinPrefix as $prefix => $join) {
  287. $joinName = $this->_getTableName($join);
  288. $sqlJoin[] = " join `{$joinName}` {$prefix} on(" . $this->_parseJoinParams($this->_joinParams[$prefix]) . ")";
  289. }
  290. $sqlJoin = (!empty($sqlJoin)) ? implode("\n\t", $sqlJoin) : "";
  291. DBG::log($this->where, 'array', "generateSql \$this->where");
  292. $sqlWhere = array_filter(
  293. array_map([$this, '_generateWhereMain'], $this->where),
  294. 'is_string'
  295. );
  296. $sqlWhere = (!empty($sqlWhere)) ? "where " . implode("\n\t and ", $sqlWhere) : '';
  297. $limit = ($this->limit < 0) ? 0 : $this->limit;
  298. $offset = ($this->offset < 0) ? 0 : $this->offset;
  299. $sqlLimit = ($limit > 0) ? "limit {$limit} offset {$offset}" : '';
  300. // TODO: split select to local and remote (use field isLocal)
  301. // TODO: $this->_hasSelectRemoteFields = false;
  302. // TODO: $this->_hasQueryRemoteFields = false;
  303. // TODO: select must contain primaryKey
  304. $sqlSelect = array_filter(
  305. array_map([$this, '_generateSelectMain'], $this->select, array_keys($this->select)),
  306. 'is_string'
  307. );
  308. $sqlSelect = (!empty($sqlSelect))
  309. ? implode("\n\t and ", $sqlSelect)
  310. : "{$this->_fromPrefix}.*"
  311. ;
  312. $sqlOrderBy = $this->generateOrderBySql();
  313. return "
  314. select {$sqlSelect}
  315. from `{$tableName}` {$this->_fromPrefix}
  316. {$sqlJoin}
  317. {$sqlWhere}
  318. {$sqlOrderBy}
  319. {$sqlLimit}
  320. ";
  321. }
  322. public function parseSelectFieldValueToSql($fieldName, $prefix = 't') {
  323. if (false !== strpos($fieldName, '/')) {
  324. DBG::log($fieldName, 'string', "TODO: select by xpath");
  325. throw new Exception("Not implemented select by xpath ('{$fieldName}')");
  326. }
  327. $fieldType = $this->from->getXsdFieldType($fieldName);
  328. if ('xsd:' === substr($fieldType, 0, 4)) {
  329. return "{$prefix}.`{$fieldName}`";
  330. }
  331. switch ($fieldType) {
  332. case 'gml:PolygonPropertyType':
  333. case 'gml:PointPropertyType':
  334. case 'gml:LineStringPropertyType':
  335. case 'gml:GeometryPropertyType': return "AsWKT({$prefix}.`{$fieldName}`) as `{$fieldName}`";
  336. case 'p5:enum': { // TODO: check if local or remote
  337. return "{$prefix}.`{$fieldName}`";
  338. }
  339. }
  340. return null;
  341. }
  342. }