AclQueryBuilder.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. public $orderBy;
  11. public $groupBy;
  12. public $limit;
  13. public $offset;
  14. public $_fromPrefix;
  15. public $_joinPrefix;
  16. public $_joinParams;
  17. public $isInstances;
  18. public $isNotInstances;
  19. public function __construct() {
  20. $this->select = [];
  21. $this->from = null; // (ACL | tableName)
  22. $this->where = [];
  23. $this->orderBy = null;
  24. $this->groupBy = null;
  25. $this->limit = null;
  26. $this->offset = null;
  27. $this->_fromPrefix = 't'; // prefix for this->from - default 't'
  28. $this->_joinPrefix = []; // prefix => from (Acl | tableName)
  29. $this->_joinParams = []; // prefx => params
  30. $this->isInstances = [];
  31. $this->isNotInstances = [];
  32. }
  33. public function from($from, $prefix = 't') {
  34. DBG::log([
  35. 'from instanceof Core_AclBase' => ($from instanceof Core_AclBase),
  36. 'from instanceof AntAclBase' => ($from instanceof AntAclBase),
  37. 'from instanceof TableAcl' => ($from instanceof TableAcl),
  38. ], 'array', "\$from class(".get_class($from).")");
  39. if ($this->from) throw new Exception("Duplicate FROM");
  40. $this->from = $from;
  41. $this->_fromPrefix = $prefix;
  42. return $this;
  43. }
  44. public function select($propertyName) { // TODO: ogc:propertyName, *, xpath, @instances, etc...
  45. if (empty($propertyName)) return $this; // SKIP empty values, null's, etc.
  46. DBG::log($propertyName, 'array', "AclQueryBuilder->select");
  47. if (is_array($propertyName) && !empty($propertyName['rawSelect'])) {
  48. $this->select['__rawSelect__'] = $propertyName['rawSelect'];
  49. return $this;
  50. }
  51. if (!in_array($propertyName, $this->select)) $this->select[] = $propertyName; // TODO: split by property source
  52. return $this;
  53. }
  54. public function where($fieldName, $comparisonSign = null, $value = null) {
  55. if (!in_array($comparisonSign, [
  56. '=', '>=', '<=', '<>', '!='
  57. , 'like', 'not like'
  58. , 'is not null', 'is null'
  59. , 'Intersects', 'GeometryType'
  60. ])) {
  61. throw new Exception("Not implemented comparisonSign '{$comparisonSign}'");
  62. }
  63. $sqlFieldName = $fieldName; // TODO: getSqlFieldName
  64. switch ($comparisonSign) {
  65. case 'is not null': $this->where[] = "{$this->_fromPrefix}.{$sqlFieldName} is not null"; break;
  66. case 'is null': $this->where[] = "{$this->_fromPrefix}.{$sqlFieldName} is null"; break;
  67. case 'Intersects': $this->where[] = "Intersects(GeomFromText('{$value}'), {$this->_fromPrefix}.`{$sqlFieldName}`)=1"; break;
  68. case 'GeometryType': $this->where[] = "GeometryType({$this->_fromPrefix}.`{$sqlFieldName}`)='{$value}'"; break;
  69. default: $this->where[] = "{$this->_fromPrefix}.{$sqlFieldName} {$comparisonSign} " . DB::getPDO()->quote($value);
  70. }
  71. return $this;
  72. }
  73. public function whereIsNotNull($fieldName) {
  74. $this->where[] = "{$this->_fromPrefix}.{$fieldName} is not null";
  75. return $this;
  76. }
  77. public function whereRaw($rawWhere) {
  78. $this->where[] = $rawWhere;
  79. return $this;
  80. }
  81. // public function whereFunction($column, $operator = null, $value = null) {
  82. public function whereFunction($fieldName, $comparisonSign = null, $value = null) {
  83. throw new Exception("whereFunction not supported");
  84. $this->where[] = '';
  85. return $this;
  86. }
  87. public function join($join, $prefix, $params) {
  88. if (array_key_exists($prefix, $this->_joinPrefix)) throw new Exception("Prefix already used!");
  89. $this->_joinPrefix[$prefix] = $join;
  90. $this->_joinParams[$prefix] = $params;
  91. return $this;
  92. }
  93. public function orderBy($orderBy) { // TODO: ogc: order by ...
  94. if (null !== $this->orderBy) throw new Exception("OrderBy already set!");
  95. $this->orderBy = [];
  96. if (!$orderBy) return $this;
  97. // ID A,COL_X D,COL_Y A,...
  98. $sortByEx = array_map('trim', explode(',', $orderBy));
  99. $sortByEx = array_filter($sortByEx, function ($part) { return !empty($part); });
  100. foreach ($sortByEx as $sortPart) {
  101. $sortPartEx = explode(' ', $sortPart);
  102. if (count($sortPartEx) > 2) throw new Exception("SortBy parse error #" . __LINE__);
  103. $fieldName = trim($sortPartEx[0]);
  104. if (!$this->isFieldAllowedToOrderBy($fieldName)) throw new Exception("SortBy parse error for field '{$fieldName}' #" . __LINE__);
  105. $colSortDir = 'ASC';
  106. if (count($sortPartEx) == 2) {
  107. if ('A' == strtoupper($sortPartEx[1]) || 'ASC' == strtoupper($sortPartEx[1])) {
  108. } else if ('D' == strtoupper($sortPartEx[1]) || 'DESC' == strtoupper($sortPartEx[1])) {
  109. $colSortDir = 'DESC';
  110. } else throw new Exception("SortBy parse error - unknown sort order '{$sortPartEx[1]}' #" . __LINE__);
  111. }
  112. $this->orderBy[] = [$fieldName, $colSortDir];
  113. }
  114. return $this;
  115. }
  116. public function isFieldAllowedToOrderBy($fieldName) {
  117. return true;
  118. }
  119. public function generateOrderBySql() {
  120. if (empty($this->orderBy)) return '';
  121. $sortByList = [];
  122. foreach ($this->orderBy as $orderBy) {
  123. $sortByList[] = "t.`{$orderBy[0]}` {$orderBy[1]}";
  124. }
  125. return (!empty($sortByList))
  126. ? "order by " . implode(", ", $sortByList)
  127. : '';
  128. }
  129. public function limit($limit) {
  130. $this->limit = (int)$limit;
  131. return $this;
  132. }
  133. public function offset($offset) {
  134. $this->offset = (int)$offset;
  135. return $this;
  136. }
  137. public function isInstance($instances) {
  138. $this->isInstances = (is_array($instances)) ? $instances : [ $instances ];
  139. return $this;
  140. }
  141. public function isNotInstance($instances) {
  142. $this->isNotInstances = (is_array($instances)) ? $instances : [ $instances ];
  143. return $this;
  144. }
  145. public function _parseJoinParams($params) {
  146. if (array_key_exists('rawJoin', $params)) return $params['rawJoin'];
  147. throw new Exception("Not implemented JOIN params '".json_encode($params)."'");
  148. }
  149. public function _getTableName($source) {
  150. if (is_scalar($source)) return $source;
  151. if ($source instanceof Core_AclBase) return $source->getRootTableName();
  152. throw new Exception("Not implemented FROM type '".get_class($source)."'");
  153. }
  154. public function execute() {
  155. return $this->fetchAll();
  156. }
  157. public function fetchAll() {
  158. $sql = $this->generateSql();
  159. DBG::log((array)$this, 'array', "AclQueryBuilder::fetchAll");
  160. return DB::getPDO()->fetchAll($sql);
  161. }
  162. public function fetchValue() {
  163. $sql = $this->generateSql();
  164. DBG::log((array)$this, 'array', "AclQueryBuilder::fetchValue");
  165. return DB::getPDO()->fetchValue($sql);
  166. }
  167. public function generateSql() {
  168. if (!$this->from) throw new Exception("Missing FROM");
  169. $tableName = $this->_getTableName($this->from);
  170. if (!$tableName) throw new Exception("Missing FROM table name");
  171. $sqlPk = 'ID';
  172. if ($this->from instanceof Core_AclBase) $sqlPk = $this->from->getSqlPrimaryKeyField();
  173. $sqlJoin = [];
  174. DBG::log($this, 'array', '$this');
  175. foreach ($this->isInstances as $k => $ns) {
  176. $idInstance = ACL::getInstanceId($ns);
  177. $instanceTable = ACL::getInstanceTable($ns);
  178. // ->join($instanceTable, 'i', [ 'rawJoin' => "i.pk = t.{$sqlPk} and i.idInstance = {$idInstance}" ])
  179. $prefix = "is_inst_{$k}";
  180. // $sqlJoin[] = " inner join `{$joinName}` {$prefix} on (
  181. // {$prefix}.pk = {$this->_fromPrefix}.{$sqlPk}
  182. // and {$prefix}.idInstance = {$idInstance}
  183. // )";
  184. $this->where[] = "{$this->_fromPrefix}.{$sqlPk} in (
  185. select {$prefix}.pk
  186. from `{$instanceTable}` {$prefix}
  187. where {$prefix}.idInstance = {$idInstance}
  188. )";
  189. DBG::log("{$this->_fromPrefix}.{$sqlPk} in (
  190. select {$prefix}.pk
  191. from `{$instanceTable}` {$prefix}
  192. where {$prefix}.idInstance = {$idInstance}
  193. )", 'string', "\$this->where[] =");
  194. }
  195. foreach ($this->isNotInstances as $k => $ns) {
  196. $idInstance = ACL::getInstanceId($ns);
  197. $instanceTable = ACL::getInstanceTable($ns);
  198. // ->join($instanceTable, 'i', [ 'rawJoin' => "i.pk = t.{$sqlPk} and i.idInstance = {$idInstance}" ])
  199. $prefix = "is_inst_{$k}";
  200. // $sqlJoin[] = " inner join `{$joinName}` {$prefix} on (
  201. // {$prefix}.pk = {$this->_fromPrefix}.{$sqlPk}
  202. // and {$prefix}.idInstance = {$idInstance}
  203. // )";
  204. $this->where[] = "{$this->_fromPrefix}.{$sqlPk} not in (
  205. select {$prefix}.pk
  206. from `{$instanceTable}` {$prefix}
  207. where {$prefix}.idInstance = {$idInstance}
  208. )";
  209. }
  210. // join `{$instanceTable}` i on(i.pk = t.{$sqlPk} and i.idInstance = {$idInstance})
  211. foreach ($this->_joinPrefix as $prefix => $join) {
  212. $joinName = $this->_getTableName($join);
  213. $sqlJoin[] = " join `{$joinName}` {$prefix} on(" . $this->_parseJoinParams($this->_joinParams[$prefix]) . ")";
  214. }
  215. $sqlJoin = (!empty($sqlJoin)) ? implode("\n\t", $sqlJoin) : "";
  216. $sqlWhere = [];
  217. foreach ($this->where as $where) {
  218. $sqlWhere[] = $where;
  219. }
  220. $sqlWhere = (!empty($sqlWhere)) ? "where " . implode("\n\t and ", $sqlWhere) : '';
  221. $limit = ($this->limit < 0) ? 0 : $this->limit;
  222. $offset = ($this->offset < 0) ? 0 : $this->offset;
  223. $sqlLimit = ($limit > 0) ? "limit {$limit} offset {$offset}" : '';
  224. $sqlSelect = [];
  225. if (!empty($this->select['__rawSelect__'])) {
  226. $sqlSelect[] = $this->select['__rawSelect__'];
  227. } else {
  228. $sqlSelect[] = "{$this->_fromPrefix}.{$sqlPk}";
  229. if (in_array('*', $this->select)) $sqlSelect[] = "{$this->_fromPrefix}.*";
  230. }
  231. if (in_array('@instances', $this->select)) {
  232. if (!($this->from instanceof Core_AclBase)) throw new Exception("select @instances allowed only for Acl object");
  233. $instanceTable = ACL::getInstanceTable($this->from->getNamespace());
  234. $sqlSelect[] = "
  235. (
  236. select GROUP_CONCAT(inst_conf.namespace)
  237. from `{$instanceTable}` inst_tbl
  238. join `CRM_INSTANCE_CONFIG` inst_conf on (inst_conf.id = inst_tbl.idInstance)
  239. where inst_tbl.pk = {$this->_fromPrefix}.{$sqlPk}
  240. ) as `@instances`
  241. ";
  242. }
  243. $sqlOrderBy = $this->generateOrderBySql();
  244. $sqlSelect = (!empty($sqlSelect)) ? implode(", ", $sqlSelect) : "{$this->_fromPrefix}.*";
  245. return "
  246. select {$sqlSelect}
  247. from `{$tableName}` {$this->_fromPrefix}
  248. {$sqlJoin}
  249. {$sqlWhere}
  250. {$sqlOrderBy}
  251. {$sqlLimit}
  252. ";
  253. }
  254. }