RefConfig.php 23 KB

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