RefConfig.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. <?php
  2. Lib::loadClass('Type_Field');
  3. Lib::loadClass('Type_RefConfig');
  4. Lib::loadClass('Api_WfsNs');
  5. Lib::loadClass('ACL');
  6. /*
  7. RefStorage - for ref data manipulation
  8. RefConfig - for ref config
  9. `CRM_REF_CONFIG`:
  10. - `ID`: primaryKey (used to generate **Storage** name for data)
  11. - `ROOT_OBJECT_NS`: root object namespace
  12. - `CHILD_NAME`: child typeName (or alias name - not supported yet)
  13. - `CHILD_NS`: child namespace (required when use `CHILD_NAME` as alias)
  14. - `A_STATUS`: status
  15. - 'WAITING': not Active, 'NORMAL': Active, 'DELETED': removed
  16. - `VERSION`: **Storage** version
  17. - `A_LAST_ACTION_DATE`: last action timestamp
  18. - `SOURCE`: place where data is stored
  19. - 'table': table with data
  20. - 'view': view by flat relation cache
  21. - 'backRef': view on ref table with replaced fields
  22. **Storage** - table or view - place where data is stored
  23. RefConfig::isActive($objectNamespace, $childTypeName) // Ref is active when: CRM_REF_CONFIG.A_STATUS = NORMAL
  24. RefConfig::getRefTable($objectNamespace, $childTypeName) // ref table - TODO not needed?
  25. */
  26. class RefConfig {
  27. static $REF_TABLE_VERSION = 2;
  28. static function isActive($objectNamespace, $childTypeName) {
  29. $refInfo = self::fetch($objectNamespace, $childTypeName);
  30. return ('NORMAL' === $refInfo->status);
  31. }
  32. /** static function fetch(Type_Namespace $rootObjectNamespace, Type_TypeName $childName, Type_Namespace $childNamespace = null): Type_RefConfig */
  33. static function fetch($rootObjectNamespace, $childName, $childNamespace = null) { // @returns Type_RefConfig
  34. if (!$childTypeName) $childTypeName = Api_WfsNs::namespaceFromTypeName($fieldName);
  35. $rootObjectNamespace = ACL::getBaseNamespace($rootObjectNamespace);
  36. if (!$childNamespace) {
  37. $rootAcl = ACL::getAclByNamespace($rootObjectNamespace);
  38. $childXsdType = $rootAcl->getXsdFieldType($childName);
  39. list($typePrefix, $childNamespace) = explode(':', $childXsdType, 2);
  40. DBG::log(['$childXsdType' => $childXsdType, '$typePrefix' => $typePrefix, '$childNamespace' => $childNamespace], 'array', "DBG get ref table ...");
  41. switch ($typePrefix) {
  42. case 'ref_uri': $childAcl = ACL::getAclByNamespace($childNamespace); break;
  43. case 'ref': $childAcl = ACL::getAclByTypeName($childNamespace); break;
  44. default: throw new Exception("Expected ref type for field '{$childName}' in object '{$rootObjectNamespace}'");
  45. }
  46. }
  47. $refInfo = [];// define $refInfo = [ ID, A_STATUS, VERSION ]
  48. try {// check that ref config table exists
  49. $sqlRootTableNs = DB::getPDO()->quote($rootObjectNamespace, PDO::PARAM_STR);
  50. $sqlChildName = DB::getPDO()->quote($childName, PDO::PARAM_STR);
  51. $sqlChildNamespace = DB::getPDO()->quote($childNamespace, PDO::PARAM_STR);
  52. $refInfo = DB::getPDO()->fetchFirst("
  53. select c.ID, c.A_STATUS, c.VERSION, c.SOURCE
  54. from `CRM_REF_CONFIG` c
  55. where c.ROOT_OBJECT_NS = {$sqlRootTableNs}
  56. and c.CHILD_NAME = {$sqlChildName}
  57. and c.CHILD_NS = {$sqlChildNamespace}
  58. ");
  59. } catch (Exception $e) {
  60. DB::getPDO()->execSql("
  61. CREATE TABLE IF NOT EXISTS `CRM_REF_CONFIG` (
  62. `ID` INT NOT NULL AUTO_INCREMENT
  63. , `ROOT_OBJECT_NS` VARCHAR(255) NOT NULL
  64. , `CHILD_NAME` VARCHAR(255) NOT NULL
  65. , `CHILD_NS` VARCHAR(255) NOT NULL
  66. , `A_STATUS` enum('WAITING', 'NORMAL', 'DELETED') NOT NULL DEFAULT 'WAITING'
  67. , `VERSION` int(11) NOT NULL DEFAULT 0
  68. , `A_LAST_ACTION_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
  69. , PRIMARY KEY (`ID`)
  70. ) ENGINE = MyISAM DEFAULT CHARSET=latin2;
  71. ");
  72. try {
  73. DB::getPDO()->execSql(" ALTER TABLE `CRM_REF_CONFIG` ADD `SOURCE` enum('table', 'view') not null default 'table' ");
  74. } catch (Exception $e) {
  75. DBG::log($e);
  76. }
  77. }
  78. try {
  79. DB::getPDO()->execSql(" ALTER TABLE `CRM_REF_CONFIG` CHANGE `SOURCE` `SOURCE` enum('table', 'view', 'backRef') not null default 'table' ");
  80. } catch (Exception $e) {
  81. DBG::log($e);
  82. }
  83. if (empty($refInfo)) {
  84. $refInfo = [ 'ID' => 0, 'A_STATUS' => 'WAITING', 'VERSION' => 0, 'SOURCE' => 'table' ];
  85. $refInfo['ID'] = DB::getPDO()->insert("CRM_REF_CONFIG", [
  86. 'ROOT_OBJECT_NS' => $rootObjectNamespace,
  87. 'CHILD_NAME' => $childName,
  88. 'CHILD_NS' => $childNamespace,
  89. 'VERSION' => self::$REF_TABLE_VERSION
  90. ]);
  91. }
  92. // { // TODO: fix source if ref for `SystemObjects__x3A__*` and defined flat_relation_cache - move to AclReinstall?
  93. // if ('SystemObjects__x3A__' === substr($childNamespace, 0, strlen('SystemObjects__x3A__'))) {
  94. // if ('table' === $refInfo['SOURCE']) {
  95. // $toUpdate = [
  96. // 'SOURCE' => 'view',
  97. // 'A_STATUS' => 'WAITING',
  98. // ];
  99. // DB::getPDO()->update('CRM_REF_CONFIG', 'ID', $refInfo['ID'], $toUpdate);
  100. // $refInfo = array_merge($refInfo, $toUpdate);
  101. // }
  102. // }
  103. // }
  104. if (!$refInfo['ID']) throw new Exception("Ref table not found in ref config table for field '{$childName}' in object '{$rootObjectNamespace}'");
  105. return Type_RefConfig::build($refInfo);
  106. }
  107. static function getChildRefFullList($namespace) {
  108. $namespace = ACL::getBaseNamespace($namespace);
  109. if (!$namespace) throw new Exception("Missing namespace");
  110. return array_map('Type_RefConfig::build', DB::getPDO()->fetchAll("
  111. select c.ID
  112. , c.A_STATUS
  113. , c.SOURCE
  114. , c.CHILD_NAME
  115. from CRM_REF_CONFIG c
  116. where c.ROOT_OBJECT_NS = :namespace
  117. -- and c.A_STATUS = 'NORMAL'
  118. ", [
  119. ':namespace' => $namespace,
  120. ]));
  121. }
  122. static function isRefField($objectNamespace, $fieldName) {
  123. return (false !== strpos($fieldName, ':'));
  124. }
  125. /*
  126. @param $appInfo = [
  127. [type] => ref:default_db__x3A__BI_audit_CEIDG:BI_audit_CEIDG
  128. [minOccurs] => 0
  129. [maxOccurs] => unbounded
  130. [restrictions] => []
  131. [appInfo] => []
  132. ]
  133. */
  134. static function needUpdate($objectNamespace, $childTypeName, Type_Field $newField, Type_Field $oldField = null) {
  135. DBG::log(['objectNamespace' => $objectNamespace, 'childTypeName' => $childTypeName, 'newField' => $newField, 'oldField' => $oldField], 'array', "RefConfig::needUpdate...");
  136. if (!$oldField) throw new Exception("Missig oldField in RefConfig::needUpdate({$objectNamespace}, {$childTypeName}, ...) - TODO: fetch from #acl cache");
  137. if (!($newField instanceof Type_Field_Ref)) return false;
  138. if (!($oldField instanceof Type_Field_Ref)) return false;
  139. $oldRefActive = self::isActive($objectNamespace, $childTypeName);
  140. if (!$oldRefActive) return false; // if old not installed / adtivated then just fix struct and install
  141. $newRefSource = $newField->source;
  142. $oldRefConf = self::fetch($objectNamespace, $childTypeName);
  143. $oldRefSource = $oldRefConf->source;
  144. if ($newRefSource !== $oldRefSource) DBG::log("RefConfig::needUpdate Change ref source from '{$oldRefSource}' to '{$newRefSource}'");
  145. if ($newRefSource !== $oldRefSource) return true;
  146. return false;
  147. }
  148. static function update($objectNamespace, $childTypeName, Type_Field $newField) {
  149. if (!($newField instanceof Type_Field_Ref)) return;
  150. // $oldRefActive = self::isActive($objectNamespace, $childTypeName);
  151. // if (!$oldRefActive) return; // if old not installed / adtivated then just fix struct and install
  152. $newRefSource = $newField->source;
  153. $refConfig = self::fetch($objectNamespace, $childTypeName);
  154. $oldRefSource = $refConfig->source;
  155. if ($newRefSource !== $oldRefSource) DBG::log("RefConfig::update Change ref source from '{$oldRefSource}' to '{$newRefSource}'");
  156. { // always update ref config at reinstall - drop / create ref tables (table or view)
  157. switch ($newRefSource) {
  158. case 'table': return self::installRefTable($objectNamespace, $childTypeName, $newField, $refConfig);
  159. case 'view': return self::installRefView($objectNamespace, $childTypeName, $newField, $refConfig);
  160. case 'backRef': return self::installBackRef($objectNamespace, $childTypeName, $newField, $refConfig);
  161. }
  162. }
  163. if ($newRefSource !== $oldRefSource) {
  164. if ('table' === $oldRefSource) {
  165. // TODO: check if table has data
  166. // TODO: if no data in table then DROP ?
  167. }
  168. throw new Exception("TODO: RefConfig::update Change ref source from '{$oldRefSource}' to '{$newRefSource}' in '{$objectNamespace}'-&gt;'{$childTypeName}'");
  169. }
  170. }
  171. static function createRefTable($objectNamespace, $childTypeName, Type_RefConfig $refConfig = null) {
  172. if (!$refConfig) $refConfig = self::fetch($objectNamespace, $childTypeName);
  173. $refTableName = "CRM__#REF_TABLE__{$refConfig->id}";
  174. DB::getPDO()->execSql("
  175. CREATE TABLE IF NOT EXISTS `{$refTableName}` (
  176. `PRIMARY_KEY` int(11) NOT NULL
  177. , `REMOTE_PRIMARY_KEY` int(11) NOT NULL
  178. , `REMOTE_TYPENAME` varchar(255) NOT NULL DEFAULT ''
  179. , `A_STATUS` enum('WAITING', 'NORMAL', 'DELETED') NOT NULL DEFAULT 'WAITING'
  180. , `TRANSACTION_ID` int(11) NOT NULL
  181. , `A_LAST_ACTION_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
  182. , KEY `PRIMARY_KEY` (`PRIMARY_KEY`)
  183. , KEY `REMOTE_PRIMARY_KEY` (`REMOTE_PRIMARY_KEY`)
  184. , KEY `TRANSACTION_ID` (`TRANSACTION_ID`)
  185. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 COMMENT='{$objectNamespace} #REF {$childTypeName}';
  186. ");
  187. $affected = DB::getPDO()->update("CRM_REF_CONFIG", 'ID', $refConfig->id, [
  188. 'A_STATUS' => "NORMAL",
  189. // 'VERSION' => self::$REF_TABLE_VERSION
  190. ]);
  191. self::upgradeRefTableFrom1to2($refConfig);
  192. }
  193. static function upgradeRefTableFrom1to2(Type_RefConfig $refConfig) { // TODO: rm ACL::upgradeRefConfigFrom1to2
  194. if (1 == $refConfig->version) {
  195. if ('table' === $refConfig->source && 'NORMAL' == $refConfig->status) {
  196. $refTableName = "CRM__#REF_TABLE__{$refConfig->id}";
  197. try {
  198. DB::getPDO()->execSql(" CREATE INDEX `TRANSACTION_ID` ON `{$refTableName}` (`TRANSACTION_ID`) ");
  199. } catch (Exception $e) {
  200. DBG::log($e);
  201. }
  202. }
  203. $affected = DB::getPDO()->update("CRM_REF_CONFIG", 'ID', $refConfig->id, [
  204. 'VERSION' => 2
  205. ]);
  206. }
  207. // TODO: return array_merge($refConfig, [ 'VERSION' => 2 ]);
  208. }
  209. static function installRefTable($objectNamespace, $childTypeName, Type_Field $newField, Type_RefConfig $refConfig = null) {
  210. if (!$refConfig) $refConfig = self::fetch($objectNamespace, $childTypeName);
  211. self::createRefTable($objectNamespace, $childTypeName, $refConfig);
  212. $affected = DB::getPDO()->update("CRM_REF_CONFIG", 'ID', $refConfig->id, [
  213. 'SOURCE' => "table",
  214. 'A_STATUS' => "NORMAL",
  215. 'VERSION' => self::$REF_TABLE_VERSION,
  216. ]);
  217. }
  218. static function installRefView($objectNamespace, $childTypeName, Type_Field $typeField, Type_RefConfig $refConfig = null) {
  219. if (!$refConfig) $refConfig = self::fetch($objectNamespace, $childTypeName);
  220. $viewSelectSql = RefConfig::generateRefSelectSqlByFlatRelationCache($objectNamespace, $childTypeName, $typeField);
  221. $refTableName = "CRM__#REF_TABLE__{$refConfig->id}_VIEW";
  222. DB::getPDO()->execSql(" CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `{$refTableName}` AS {$viewSelectSql} ");
  223. $affected = DB::getPDO()->update("CRM_REF_CONFIG", 'ID', $refConfig->id, [
  224. 'SOURCE' => 'view',
  225. 'A_STATUS' => "NORMAL",
  226. ]);
  227. }
  228. static function installBackRef($objectNamespace, $childTypeName, Type_Field $newField, Type_RefConfig $refConfig = null) {
  229. $viewSelectSql = self::generateRefSelectSqlByBackRef($objectNamespace, $childTypeName);
  230. if (!$refConfig) $refConfig = self::fetch($objectNamespace, $childTypeName);
  231. $refTableName = "CRM__#REF_TABLE__{$refConfig->id}_VIEW";
  232. DB::getPDO()->execSql(" CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `{$refTableName}` AS {$viewSelectSql} ");
  233. $affected = DB::getPDO()->update("CRM_REF_CONFIG", 'ID', $refConfig->id, [
  234. 'SOURCE' => 'backRef',
  235. 'A_STATUS' => "NORMAL",
  236. 'VERSION' => self::$REF_TABLE_VERSION,
  237. ]);
  238. }
  239. static function generateRefSelectSqlByBackRef($rootObjectNamespace, $childName) {
  240. // generate view which is select from {replaced(pk, remote pk) on ref table from backRef}
  241. // {
  242. // DBG::nicePrint($refInfo, "\$refInfo");
  243. // DBG::nicePrint($rootObjectNamespace, "\$rootObjectNamespace");
  244. // DBG::nicePrint($childName, "\$childName");
  245. // DBG::nicePrint($childNamespace, "\$childNamespace");
  246. // $replacedObjNs = Api_WfsNs::namespaceFromTypeName($childName);
  247. // $replacedChildName = Api_WfsNs::typeName($rootObjectNamespace);
  248. // DBG::nicePrint($replacedObjNs, "\$replacedObjNs");
  249. // DBG::nicePrint($replacedChildName, "\$replacedChildName");
  250. // return ACL::getRefTable($replacedObjNs, $replacedChildName, 1);
  251. // throw new Exception("Not Implemented ref SOURCE = '{$refInfo['SOURCE']}'");
  252. // }
  253. $childNs = Api_WfsNs::namespaceFromTypeName($childName);
  254. $rootTypeName = Api_WfsNs::typeName($rootObjectNamespace);
  255. $backRefTable = ACL::getRefTable($childNs, $rootTypeName);
  256. DBG::nicePrint($backRefTable, "ACL::getRefTable({$childNs}, {$rootTypeName})");
  257. // TODO: check if ref_config is not backRef to avoid loop // $refInfo = self::getRefConfig($fieldNs, $item['typeName'], $item['typeName']);
  258. $lastActionDateField = "NULL"; // , IF(l.A_RECORD_UPDATE_DATE > r.A_RECORD_UPDATE_DATE, l.A_RECORD_UPDATE_DATE, r.A_RECORD_UPDATE_DATE) as A_LAST_ACTION_DATE
  259. $sql = "
  260. select backRef.REMOTE_PRIMARY_KEY as PRIMARY_KEY
  261. , backRef.PRIMARY_KEY as REMOTE_PRIMARY_KEY
  262. , backRef.REMOTE_TYPENAME as REMOTE_TYPENAME
  263. , backRef.A_STATUS as A_STATUS
  264. , 0 as TRANSACTION_ID
  265. , {$lastActionDateField} as A_LAST_ACTION_DATE
  266. from `{$backRefTable}` backRef
  267. ";
  268. DBG::log($sql, 'sql', "generateRefSelectSqlByBackRef");
  269. return $sql;
  270. }
  271. static function generateRefSelectSqlByFlatRelationCache($rootObjectNamespace, $childName, Type_Field $typeField) { // CRM_REF_CONFIG
  272. $appInfo = $typeField->appInfo;
  273. if (empty($appInfo)) throw new Exception("Empty app:info for field '{$rootObjectNamespace}/{$childName}'");
  274. DBG::log(['$appInfo'=>$appInfo, '$rootObjectNamespace'=>$rootObjectNamespace, '$childName'=>$childName], 'array', "\$appInfo");
  275. $rootAcl = ACL::getAclByNamespace($rootObjectNamespace);
  276. $childXsdType = $rootAcl->getXsdFieldType($childName);
  277. list($typePrefix, $childNamespace) = explode(':', $childXsdType, 2);
  278. switch ($typePrefix) {
  279. case 'ref_uri': $childAcl = ACL::getAclByNamespace($childNamespace); break;
  280. case 'ref': $childAcl = ACL::getAclByTypeName($childNamespace); break;
  281. default: throw new Exception("Expected ref type for field '{$childName}' in object '{$rootObjectNamespace}'");
  282. }
  283. $lastActionDateField = "NULL"; // , IF(l.A_RECORD_UPDATE_DATE > r.A_RECORD_UPDATE_DATE, l.A_RECORD_UPDATE_DATE, r.A_RECORD_UPDATE_DATE) as A_LAST_ACTION_DATE
  284. $rootPrimaryKeyField = $rootAcl->getPrimaryKeyField();
  285. $childPrimaryKeyField = $childAcl->getPrimaryKeyField();
  286. $rootTableName = $rootAcl->getRootTableName();
  287. $childTableName = $childAcl->getRootTableName();
  288. // '$appInfo' => [
  289. // 'flat_relation_cache' => [
  290. // 'source' => [
  291. // '@name' => 'ID',
  292. // '@xpath' => 'default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK/ID_PROCES',
  293. // ),
  294. // ),
  295. // ),
  296. // '$rootObjectNamespace' => 'default_db/CRM_PROCES/PROCES',
  297. // '$childName' => 'default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK',
  298. // '$appInfo' => [
  299. // 'flat_relation_cache' => [
  300. // 'source' => [
  301. // '@name' => 'ID',
  302. // '@xpath' => 'default_db__x3A__CRM_PROCES:PROCES/PARENT_ID',
  303. // ),
  304. // ),
  305. // ),
  306. // '$rootObjectNamespace' => 'default_db/CRM_PROCES/PROCES',
  307. // '$childName' => 'default_db__x3A__CRM_PROCES:PROCES',
  308. $appInfoRootFieldName = null;
  309. $appInfoChildFieldName = null;
  310. {
  311. if (empty($appInfo['flat_relation_cache']['source']['@name'])) throw new Exception("Missing flat_relation_cache/source/@name");
  312. if (empty($appInfo['flat_relation_cache']['source']['@xpath'])) throw new Exception("Missing flat_relation_cache/source/@xpath");
  313. $appInfoName = $appInfo['flat_relation_cache']['source']['@name'];
  314. $appInfoXpath = $appInfo['flat_relation_cache']['source']['@xpath'];
  315. // $rootNs = $rootAcl->getNamespace()
  316. if ("{$childName}/" === substr($appInfoXpath, 0, strlen("{$childName}/"))) {
  317. $appInfoRootFieldName = substr($appInfoXpath, strlen("{$childName}/"));
  318. $appInfoChildFieldName = $appInfoName;
  319. } else {
  320. throw new Exception("TODO parse flat_relation_cache");
  321. }
  322. }
  323. if (!$appInfoRootFieldName || !$appInfoChildFieldName) throw new Exception("Error Processing flat_relation_cache");
  324. $sqlWhereFromRestrictions = [];
  325. DBG::log(['root'=>$rootAcl->getFields(), 'child'=>$childAcl->getFields()], 'array', "rootAcl and childAcl fields - xsdRestrictions");
  326. if ($rootAcl instanceof AntAclBase && $childAcl instanceof AntAclBase) {
  327. $rootLocalFieldsWithRestrictions = array_filter($rootAcl->getFields(), function ($field) {
  328. if (!$field['isLocal']) return false;
  329. if (empty($field['xsdRestrictions'])) return false;
  330. if ('[]' == $field['xsdRestrictions']) return false;
  331. return true;
  332. });
  333. $childLocalFieldsWithRestrictions = array_filter($childAcl->getFields(), function ($field) {
  334. if (!$field['isLocal']) return false;
  335. if (empty($field['xsdRestrictions'])) return false;
  336. if ('[]' == $field['xsdRestrictions']) return false;
  337. return true;
  338. });
  339. DBG::log(['root'=>$rootLocalFieldsWithRestrictions, 'child'=>$childLocalFieldsWithRestrictions], 'array', "root and child fields with xsdRestrictions");
  340. if (!empty($rootLocalFieldsWithRestrictions)) {
  341. $sqlTablePrefix = 'root';
  342. $sqlWhereFromRestrictions = array_reduce(
  343. array_map(function ($field) use ($sqlTablePrefix) {
  344. $sqlRestrictions = [];
  345. // 'xsdRestrictions' => '{"enumeration":{"PROCES":"PROCES"}}',
  346. $restrictions = @json_decode($field['xsdRestrictions'], $assoc = true);
  347. if (!empty($restrictions)) {
  348. if (!empty($restrictions['enumeration'])) {
  349. $sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` in (" . implode(",", array_map([DB::getPDO(), 'quote'], array_keys($restrictions['enumeration']))) . ")";
  350. }
  351. }
  352. return $sqlRestrictions;
  353. }, $rootLocalFieldsWithRestrictions),
  354. function ($ret, $cur) {
  355. return array_merge($ret, array_filter($cur, ['V', 'filterNotEmpty']));
  356. },
  357. $sqlWhereFromRestrictions
  358. );
  359. }
  360. if (!empty($childLocalFieldsWithRestrictions)) {
  361. $sqlTablePrefix = 'child';
  362. $sqlWhereFromRestrictions = array_reduce(
  363. array_map(function ($field) use ($sqlTablePrefix) {
  364. $sqlRestrictions = [];
  365. // 'xsdRestrictions' => '{"enumeration":{"PROCES":"PROCES"}}',
  366. $restrictions = @json_decode($field['xsdRestrictions'], $assoc = true);
  367. if (!empty($restrictions)) {
  368. if (!empty($restrictions['enumeration'])) {
  369. $sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` in (" . implode(",", array_map([DB::getPDO(), 'quote'], array_keys($restrictions['enumeration']))) . ")";
  370. }
  371. }
  372. return $sqlRestrictions;
  373. }, $childLocalFieldsWithRestrictions),
  374. function ($ret, $cur) {
  375. return array_merge($ret, array_filter($cur, ['V', 'filterNotEmpty']));
  376. },
  377. $sqlWhereFromRestrictions
  378. );
  379. }
  380. }
  381. $sqlWhereFromRestrictions = (!empty($sqlWhereFromRestrictions)) ? implode(" and ", $sqlWhereFromRestrictions) : "1=1";
  382. $sqlChildFieldName = $childAcl->getSqlFieldName($appInfoRootFieldName);
  383. $sql = "
  384. select root.{$rootPrimaryKeyField} as PRIMARY_KEY
  385. , child.{$childPrimaryKeyField} as REMOTE_PRIMARY_KEY
  386. , '' as REMOTE_TYPENAME
  387. , 'WAITING' as A_STATUS
  388. , 0 as TRANSACTION_ID
  389. , {$lastActionDateField} as A_LAST_ACTION_DATE
  390. from `{$rootTableName}` root
  391. join `{$childTableName}` child on(child.{$sqlChildFieldName} = root.{$appInfoChildFieldName})
  392. where {$sqlWhereFromRestrictions}
  393. ";
  394. DBG::log($sql, 'sql', "generateRefSelectSqlByFlatRelationCache");
  395. return $sql;
  396. }
  397. static function remove(Type_RefConfig $refConfig) {
  398. DB::getPDO()->update('CRM_REF_CONFIG', 'ID', $refConfig->id, [
  399. 'A_STATUS' => 'DELETED',
  400. 'A_LAST_ACTION_DATE' => 'NOW()',
  401. ]);
  402. }
  403. static function reactivate(Type_RefConfig $refConfig) {
  404. DB::getPDO()->update('CRM_REF_CONFIG', 'ID', $refConfig->id, [ // TODO: update ref table, update source -- fixed below by RefConfig::update
  405. 'A_STATUS' => 'WAITING',
  406. 'A_LAST_ACTION_DATE' => 'NOW()',
  407. ]);
  408. }
  409. }