AclQueryBuilder.php 14 KB

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