RefConfig.php 20 KB

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