RefConfig.php 21 KB

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