RefConfig.php 27 KB

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