AclQueryBuilder.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. , 'or' // $value = [ comparisons for $fieldName ... or null ]
  61. , 'and' // $value = [ comparisons for $fieldName ... or null ]
  62. ])) {
  63. throw new Exception("Not implemented comparisonSign '{$comparisonSign}'");
  64. }
  65. $this->where[] = [$fieldName, $comparisonSign, $value];
  66. return $this;
  67. }
  68. public function _generateWhereMain($where) { // @returns string
  69. list($fieldName, $comparisonSign, $value) = $where;
  70. $sqlFieldName = $fieldName; // TODO: getSqlFieldName // TODO: get sql field name with table prefix from join list to replace "{$this->_fromPrefix}.{$sqlFieldName}" below
  71. switch ($comparisonSign) {
  72. case 'is not null': return "{$this->_fromPrefix}.{$sqlFieldName} is not null";
  73. case 'is null': return "{$this->_fromPrefix}.{$sqlFieldName} is null";
  74. case 'Intersects': return "Intersects(GeomFromText('{$value}'), {$this->_fromPrefix}.`{$sqlFieldName}`)=1";
  75. case 'GeometryType': return "GeometryType({$this->_fromPrefix}.`{$sqlFieldName}`)='{$value}'";
  76. case 'or': return $this->_generateWhereBlock($where);
  77. case 'and': return $this->_generateWhereBlock($where);
  78. default: return "{$this->_fromPrefix}.{$sqlFieldName} {$comparisonSign} " . DB::getPDO()->quote($value);
  79. }
  80. return null;
  81. }
  82. public function _generateWhereBlock($where) { // @returns string
  83. list($fieldName, $sqlGlue, $list) = $where;
  84. $sqlList = array_filter(
  85. array_map([$this, '_generateWhereMain'], $list),
  86. 'is_string'
  87. );
  88. if (1 === count($sqlList)) return $sqlList[0];
  89. else return "( " . implode(" {$sqlGlue} ", $sqlList) . " )";
  90. }
  91. public function whereIsNotNull($fieldName) {
  92. $this->where[] = "{$this->_fromPrefix}.{$fieldName} is not null";
  93. return $this;
  94. }
  95. public function whereRaw($rawWhere) {
  96. $this->where[] = $rawWhere;
  97. return $this;
  98. }
  99. // public function whereFunction($column, $operator = null, $value = null) {
  100. public function whereFunction($fieldName, $comparisonSign = null, $value = null) {
  101. throw new Exception("whereFunction not supported");
  102. $this->where[] = '';
  103. return $this;
  104. }
  105. public function join($join, $prefix, $params) {
  106. if (array_key_exists($prefix, $this->_joinPrefix)) throw new Exception("Prefix already used!");
  107. $this->_joinPrefix[$prefix] = $join;
  108. $this->_joinParams[$prefix] = $params;
  109. return $this;
  110. }
  111. public function orderBy($orderBy) { // TODO: ogc: order by ...
  112. if (null !== $this->orderBy) throw new Exception("OrderBy already set!");
  113. $this->orderBy = [];
  114. if (!$orderBy) return $this;
  115. // ID A,COL_X D,COL_Y A,...
  116. $sortByEx = array_map('trim', explode(',', $orderBy));
  117. $sortByEx = array_filter($sortByEx, function ($part) { return !empty($part); });
  118. foreach ($sortByEx as $sortPart) {
  119. $sortPartEx = explode(' ', $sortPart);
  120. if (count($sortPartEx) > 2) throw new Exception("SortBy parse error #" . __LINE__);
  121. $fieldName = trim($sortPartEx[0]);
  122. if (!$this->isFieldAllowedToOrderBy($fieldName)) throw new Exception("SortBy parse error for field '{$fieldName}' #" . __LINE__);
  123. $colSortDir = 'ASC';
  124. if (count($sortPartEx) == 2) {
  125. if ('A' == strtoupper($sortPartEx[1]) || 'ASC' == strtoupper($sortPartEx[1])) {
  126. } else if ('D' == strtoupper($sortPartEx[1]) || 'DESC' == strtoupper($sortPartEx[1])) {
  127. $colSortDir = 'DESC';
  128. } else throw new Exception("SortBy parse error - unknown sort order '{$sortPartEx[1]}' #" . __LINE__);
  129. }
  130. $this->orderBy[] = [$fieldName, $colSortDir];
  131. }
  132. return $this;
  133. }
  134. public function isFieldAllowedToOrderBy($fieldName) {
  135. return true;
  136. }
  137. public function generateOrderBySql() {
  138. if (empty($this->orderBy)) return '';
  139. $sortByList = [];
  140. foreach ($this->orderBy as $orderBy) {
  141. $sortByList[] = "t.`{$orderBy[0]}` {$orderBy[1]}";
  142. }
  143. return (!empty($sortByList))
  144. ? "order by " . implode(", ", $sortByList)
  145. : '';
  146. }
  147. public function limit($limit) {
  148. $this->limit = (int)$limit;
  149. return $this;
  150. }
  151. public function offset($offset) {
  152. $this->offset = (int)$offset;
  153. return $this;
  154. }
  155. public function isInstance($instances) {
  156. $this->isInstances = (is_array($instances)) ? $instances : [ $instances ];
  157. return $this;
  158. }
  159. public function isNotInstance($instances) {
  160. $this->isNotInstances = (is_array($instances)) ? $instances : [ $instances ];
  161. return $this;
  162. }
  163. public function _parseJoinParams($params) {
  164. if (array_key_exists('rawJoin', $params)) return $params['rawJoin'];
  165. throw new Exception("Not implemented JOIN params '".json_encode($params)."'");
  166. }
  167. public function _getTableName($source) {
  168. if (is_scalar($source)) return $source;
  169. if ($source instanceof Core_AclBase) return $source->getRootTableName();
  170. throw new Exception("Not implemented FROM type '".get_class($source)."'");
  171. }
  172. public function execute() {
  173. return $this->fetchAll();
  174. }
  175. public function fetchAll() {
  176. $sql = $this->generateSql();
  177. DBG::log((array)$this, 'array', "AclQueryBuilder::fetchAll");
  178. return DB::getPDO()->fetchAll($sql);
  179. }
  180. public function fetchValue() {
  181. $sql = $this->generateSql();
  182. DBG::log((array)$this, 'array', "AclQueryBuilder::fetchValue");
  183. return DB::getPDO()->fetchValue($sql);
  184. }
  185. public function generateSql() {
  186. if (!$this->from) throw new Exception("Missing FROM");
  187. $tableName = $this->_getTableName($this->from);
  188. if (!$tableName) throw new Exception("Missing FROM table name");
  189. $sqlPk = 'ID';
  190. if ($this->from instanceof Core_AclBase) $sqlPk = $this->from->getSqlPrimaryKeyField();
  191. $sqlJoin = [];
  192. DBG::log($this, 'array', '$this');
  193. foreach ($this->isInstances as $k => $ns) {
  194. $idInstance = ACL::getInstanceId($ns);
  195. $instanceTable = ACL::getInstanceTable($ns);
  196. // ->join($instanceTable, 'i', [ 'rawJoin' => "i.pk = t.{$sqlPk} and i.idInstance = {$idInstance}" ])
  197. $prefix = "is_inst_{$k}";
  198. // $sqlJoin[] = " inner join `{$joinName}` {$prefix} on (
  199. // {$prefix}.pk = {$this->_fromPrefix}.{$sqlPk}
  200. // and {$prefix}.idInstance = {$idInstance}
  201. // )";
  202. $this->where[] = "{$this->_fromPrefix}.{$sqlPk} in (
  203. select {$prefix}.pk
  204. from `{$instanceTable}` {$prefix}
  205. where {$prefix}.idInstance = {$idInstance}
  206. )";
  207. DBG::log("{$this->_fromPrefix}.{$sqlPk} in (
  208. select {$prefix}.pk
  209. from `{$instanceTable}` {$prefix}
  210. where {$prefix}.idInstance = {$idInstance}
  211. )", 'string', "\$this->where[] =");
  212. }
  213. foreach ($this->isNotInstances as $k => $ns) {
  214. $idInstance = ACL::getInstanceId($ns);
  215. $instanceTable = ACL::getInstanceTable($ns);
  216. // ->join($instanceTable, 'i', [ 'rawJoin' => "i.pk = t.{$sqlPk} and i.idInstance = {$idInstance}" ])
  217. $prefix = "is_inst_{$k}";
  218. // $sqlJoin[] = " inner join `{$joinName}` {$prefix} on (
  219. // {$prefix}.pk = {$this->_fromPrefix}.{$sqlPk}
  220. // and {$prefix}.idInstance = {$idInstance}
  221. // )";
  222. $this->where[] = "{$this->_fromPrefix}.{$sqlPk} not in (
  223. select {$prefix}.pk
  224. from `{$instanceTable}` {$prefix}
  225. where {$prefix}.idInstance = {$idInstance}
  226. )";
  227. }
  228. // join `{$instanceTable}` i on(i.pk = t.{$sqlPk} and i.idInstance = {$idInstance})
  229. foreach ($this->_joinPrefix as $prefix => $join) {
  230. $joinName = $this->_getTableName($join);
  231. $sqlJoin[] = " join `{$joinName}` {$prefix} on(" . $this->_parseJoinParams($this->_joinParams[$prefix]) . ")";
  232. }
  233. $sqlJoin = (!empty($sqlJoin)) ? implode("\n\t", $sqlJoin) : "";
  234. $sqlWhere = array_filter(
  235. array_map([$this, '_generateWhereMain'], $this->where),
  236. 'is_string'
  237. );
  238. $sqlWhere = (!empty($sqlWhere)) ? "where " . implode("\n\t and ", $sqlWhere) : '';
  239. $limit = ($this->limit < 0) ? 0 : $this->limit;
  240. $offset = ($this->offset < 0) ? 0 : $this->offset;
  241. $sqlLimit = ($limit > 0) ? "limit {$limit} offset {$offset}" : '';
  242. $sqlSelect = [];
  243. if (!empty($this->select['__rawSelect__'])) {
  244. $sqlSelect[] = $this->select['__rawSelect__'];
  245. } else {
  246. $sqlSelect[] = "{$this->_fromPrefix}.{$sqlPk}";
  247. if (in_array('*', $this->select)) $sqlSelect[] = "{$this->_fromPrefix}.*";
  248. }
  249. if (in_array('@instances', $this->select)) {
  250. if (!($this->from instanceof Core_AclBase)) throw new Exception("select @instances allowed only for Acl object");
  251. $instanceTable = ACL::getInstanceTable($this->from->getNamespace());
  252. $sqlSelect[] = "
  253. (
  254. select GROUP_CONCAT(inst_conf.namespace)
  255. from `{$instanceTable}` inst_tbl
  256. join `CRM_INSTANCE_CONFIG` inst_conf on (inst_conf.id = inst_tbl.idInstance)
  257. where inst_tbl.pk = {$this->_fromPrefix}.{$sqlPk}
  258. ) as `@instances`
  259. ";
  260. }
  261. $sqlOrderBy = $this->generateOrderBySql();
  262. $sqlSelect = (!empty($sqlSelect)) ? implode(", ", $sqlSelect) : "{$this->_fromPrefix}.*";
  263. return "
  264. select {$sqlSelect}
  265. from `{$tableName}` {$this->_fromPrefix}
  266. {$sqlJoin}
  267. {$sqlWhere}
  268. {$sqlOrderBy}
  269. {$sqlLimit}
  270. ";
  271. }
  272. }