RefConfig.php 25 KB

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