AclQueryBuilder.php 13 KB

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