RefConfig.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 = 4;
  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. }
  185. static function upgradeRefTableFrom1to2(Type_RefConfig $refConfig) { // TODO: rm ACL::upgradeRefConfigFrom1to2
  186. if (1 == $refConfig->version) {
  187. if ('table' === $refConfig->source && 'NORMAL' == $refConfig->status) {
  188. try {
  189. DB::getPDO()->execSql(" CREATE INDEX `TRANSACTION_ID` ON `{$refConfig->tableName}` (`TRANSACTION_ID`) ");
  190. } catch (Exception $e) {
  191. DBG::log($e);
  192. }
  193. }
  194. $affected = DB::getPDO()->update("CRM_REF_CONFIG", 'ID', $refConfig->id, [
  195. 'VERSION' => 2
  196. ]);
  197. }
  198. // TODO: return array_merge($refConfig, [ 'VERSION' => 2 ]);
  199. }
  200. static function installRefTable($objectNamespace, $childTypeName, Type_Field $newField, Type_RefConfig $refConfig = null) {
  201. if (!$refConfig) $refConfig = self::fetch($objectNamespace, $childTypeName);
  202. self::createRefTable($objectNamespace, $childTypeName, $refConfig);
  203. $affected = DB::getPDO()->update("CRM_REF_CONFIG", 'ID', $refConfig->id, [
  204. 'SOURCE' => "table",
  205. 'A_STATUS' => "NORMAL",
  206. 'VERSION' => self::$REF_TABLE_VERSION,
  207. ]);
  208. }
  209. static function installRefView($objectNamespace, $childTypeName, Type_Field $typeField, Type_RefConfig $refConfig = null) {
  210. if (!$refConfig) $refConfig = self::fetch($objectNamespace, $childTypeName);
  211. Lib::loadClass('SchemaFactory');
  212. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($objectNamespace, [ 'propertyName' => '*,field' ]);
  213. $appInfo = (!empty($item['appInfo'])) ? @json_decode($item['appInfo'], $assoc = true) : null;
  214. $charset = (!empty($appInfo) && !empty($appInfo['table_structure']['@charset'])) ? $appInfo['table_structure']['@charset'] : null;
  215. $viewSelectSql = RefConfig::generateRefSelectSqlByFlatRelationCache($objectNamespace, $childTypeName, $typeField, $charset);
  216. $refTableViewName = Type_RefConfig::generateTableName($refConfig->id, 'view');
  217. DB::getPDO()->execSql(" CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `{$refTableViewName}` AS {$viewSelectSql} ");
  218. $affected = DB::getPDO()->update("CRM_REF_CONFIG", 'ID', $refConfig->id, [
  219. 'SOURCE' => 'view',
  220. 'A_STATUS' => "NORMAL",
  221. 'VERSION' => self::$REF_TABLE_VERSION,
  222. ]);
  223. }
  224. static function installBackRef($objectNamespace, $childTypeName, Type_Field $newField, Type_RefConfig $refConfig = null) {
  225. $viewSelectSql = self::generateRefSelectSqlByBackRef($objectNamespace, $childTypeName);
  226. if (!$refConfig) $refConfig = self::fetch($objectNamespace, $childTypeName);
  227. $backRefTableViewName = Type_RefConfig::generateTableName($refConfig->id, 'backRef');
  228. DB::getPDO()->execSql(" CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `{$backRefTableViewName}` AS {$viewSelectSql} ");
  229. $affected = DB::getPDO()->update("CRM_REF_CONFIG", 'ID', $refConfig->id, [
  230. 'SOURCE' => 'backRef',
  231. 'A_STATUS' => "NORMAL",
  232. 'VERSION' => self::$REF_TABLE_VERSION,
  233. ]);
  234. }
  235. static function generateRefSelectSqlByBackRef($rootObjectNamespace, $childName) {
  236. // generate view which is select from {replaced(pk, remote pk) on ref table from backRef}
  237. // {
  238. // DBG::nicePrint($refInfo, "\$refInfo");
  239. // DBG::nicePrint($rootObjectNamespace, "\$rootObjectNamespace");
  240. // DBG::nicePrint($childName, "\$childName");
  241. // DBG::nicePrint($childNamespace, "\$childNamespace");
  242. // $replacedObjNs = Api_WfsNs::namespaceFromTypeName($childName);
  243. // $replacedChildName = Api_WfsNs::typeName($rootObjectNamespace);
  244. // DBG::nicePrint($replacedObjNs, "\$replacedObjNs");
  245. // DBG::nicePrint($replacedChildName, "\$replacedChildName");
  246. // return ACL::getRefTable($replacedObjNs, $replacedChildName, 1);
  247. // throw new Exception("Not Implemented ref SOURCE = '{$refInfo['SOURCE']}'");
  248. // }
  249. $childNs = Api_WfsNs::namespaceFromTypeName($childName);
  250. $rootTypeName = Api_WfsNs::typeName($rootObjectNamespace);
  251. // $refConfig = self::getRefConfig($childNs, $rootTypeName); // NOTE: Uwaga getRefConfig recurence loop
  252. $refConfig = self::fetch($childNs, $rootTypeName);
  253. if ('WAITING' == $refConfig->status || $refConfig->version < self::$REF_TABLE_VERSION) {
  254. throw new Exception("Error: Install/Update ref table from {$childNs} to {$rootTypeName} first");
  255. }
  256. $backRefTable = $refConfig->tableName;
  257. DBG::log($backRefTable, 'array', "ACL::getRefTable({$childNs}, {$rootTypeName})");
  258. // TODO: check if ref_config is not backRef to avoid loop // $refInfo = self::getRefConfig($fieldNs, $item['typeName'], $item['typeName']);
  259. $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
  260. $sql = "
  261. select backRef.REMOTE_PRIMARY_KEY as PRIMARY_KEY
  262. , backRef.PRIMARY_KEY as REMOTE_PRIMARY_KEY
  263. , backRef.REMOTE_TYPENAME as REMOTE_TYPENAME
  264. , backRef.A_STATUS as A_STATUS
  265. , 0 as TRANSACTION_ID
  266. , {$lastActionDateField} as A_LAST_ACTION_DATE
  267. from `{$backRefTable}` backRef
  268. ";
  269. DBG::log($sql, 'sql', "generateRefSelectSqlByBackRef");
  270. return $sql;
  271. }
  272. static function generateRefSelectSqlByFlatRelationCache($rootObjectNamespace, $childName, Type_Field $typeField, $charset = 'utf8') { // CRM_REF_CONFIG
  273. $appInfo = $typeField->appInfo;
  274. if (empty($appInfo)) throw new Exception("Empty app:info for field '{$rootObjectNamespace}/{$childName}'");
  275. DBG::log(['$appInfo'=>$appInfo, '$rootObjectNamespace'=>$rootObjectNamespace, '$childName'=>$childName], 'array', "\$appInfo");
  276. $rootAcl = ACL::getAclByNamespace($rootObjectNamespace);
  277. $childXsdType = $rootAcl->getXsdFieldType($childName);
  278. list($typePrefix, $childNamespace) = explode(':', $childXsdType, 2);
  279. switch ($typePrefix) {
  280. case 'ref_uri': $childAcl = ACL::getAclByNamespace($childNamespace); break;
  281. case 'ref': $childAcl = ACL::getAclByTypeName($childNamespace); break;
  282. default: throw new Exception("Expected ref type for field '{$childName}' in object '{$rootObjectNamespace}'");
  283. }
  284. $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
  285. $rootPrimaryKeyField = $rootAcl->getPrimaryKeyField();
  286. $childPrimaryKeyField = $childAcl->getPrimaryKeyField();
  287. $rootTableName = $rootAcl->getRootTableName();
  288. $childTableName = $childAcl->getRootTableName();
  289. // '$appInfo' => [
  290. // 'flat_relation_cache' => [
  291. // 'source' => [
  292. // '@name' => 'ID',
  293. // '@xpath' => 'default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK/ID_PROCES',
  294. // ),
  295. // ),
  296. // ),
  297. // '$rootObjectNamespace' => 'default_db/CRM_PROCES/PROCES',
  298. // '$childName' => 'default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK',
  299. // '$appInfo' => [
  300. // 'flat_relation_cache' => [
  301. // 'source' => [
  302. // '@name' => 'ID',
  303. // '@xpath' => 'default_db__x3A__CRM_PROCES:PROCES/PARENT_ID',
  304. // ),
  305. // ),
  306. // ),
  307. // '$rootObjectNamespace' => 'default_db/CRM_PROCES/PROCES',
  308. // '$childName' => 'default_db__x3A__CRM_PROCES:PROCES',
  309. $appInfoRootFieldName = null;
  310. $appInfoChildFieldName = null;
  311. {
  312. if (empty($appInfo['flat_relation_cache']['source']['@name'])) throw new Exception("Missing flat_relation_cache/source/@name");
  313. if (empty($appInfo['flat_relation_cache']['source']['@xpath'])) throw new Exception("Missing flat_relation_cache/source/@xpath");
  314. $appInfoName = $appInfo['flat_relation_cache']['source']['@name'];
  315. $appInfoXpath = $appInfo['flat_relation_cache']['source']['@xpath'];
  316. // $rootNs = $rootAcl->getNamespace()
  317. if ("{$childName}/" === substr($appInfoXpath, 0, strlen("{$childName}/"))) {
  318. $appInfoRootFieldName = substr($appInfoXpath, strlen("{$childName}/"));
  319. $appInfoChildFieldName = $appInfoName;
  320. } else {
  321. throw new Exception("TODO parse flat_relation_cache");
  322. }
  323. }
  324. if (!$appInfoRootFieldName || !$appInfoChildFieldName) throw new Exception("Error Processing flat_relation_cache");
  325. $sqlWhereFromRestrictions = [];
  326. DBG::log(['root'=>$rootAcl->getFields(), 'child'=>$childAcl->getFields()], 'array', "rootAcl and childAcl fields - xsdRestrictions");
  327. if ($rootAcl instanceof AntAclBase && $childAcl instanceof AntAclBase) {
  328. $rootLocalFieldsWithRestrictions = array_filter($rootAcl->getFields(), function ($field) {
  329. if (!$field['isLocal']) return false;
  330. if (empty($field['xsdRestrictions'])) return false;
  331. if ('[]' == $field['xsdRestrictions']) return false;
  332. return true;
  333. });
  334. $childLocalFieldsWithRestrictions = array_filter($childAcl->getFields(), function ($field) {
  335. if (!$field['isLocal']) return false;
  336. if (empty($field['xsdRestrictions'])) return false;
  337. if ('[]' == $field['xsdRestrictions']) return false;
  338. return true;
  339. });
  340. DBG::log(['root'=>$rootLocalFieldsWithRestrictions, 'child'=>$childLocalFieldsWithRestrictions], 'array', "root and child fields with xsdRestrictions");
  341. if (!empty($rootLocalFieldsWithRestrictions)) {
  342. $sqlTablePrefix = 'root';
  343. $sqlWhereFromRestrictions = array_reduce(
  344. array_map(function ($field) use ($sqlTablePrefix, $charset) {
  345. $sqlRestrictions = [];
  346. // 'xsdRestrictions' => '{"enumeration":{"PROCES":"PROCES"}}',
  347. $restrictions = @json_decode($field['xsdRestrictions'], $assoc = true);
  348. if (!empty($restrictions)) {
  349. if (!empty($restrictions['enumeration'])) {
  350. $sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` in (" . implode(",", array_map(function ($option) use ($charset) {
  351. return ($charset && $charset !== 'utf8')
  352. ? "CONVERT(" . DB::getPDO()->quote($option) . " using {$charset})"
  353. : DB::getPDO()->quote($option);
  354. }, array_keys($restrictions['enumeration']))) . ")";
  355. }
  356. if (array_key_exists('minInclusive', $restrictions)) {
  357. $minInclusive = (int)$restrictions['minInclusive'];
  358. $sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` > {$minInclusive}";
  359. }
  360. }
  361. return $sqlRestrictions;
  362. }, $rootLocalFieldsWithRestrictions),
  363. function ($ret, $cur) {
  364. return array_merge($ret, array_filter($cur, ['V', 'filterNotEmpty']));
  365. },
  366. $sqlWhereFromRestrictions
  367. );
  368. }
  369. if (!empty($childLocalFieldsWithRestrictions)) {
  370. $sqlTablePrefix = 'child';
  371. $sqlWhereFromRestrictions = array_reduce(
  372. array_map(function ($field) use ($sqlTablePrefix, $charset) {
  373. $sqlRestrictions = [];
  374. // 'xsdRestrictions' => '{"enumeration":{"PROCES":"PROCES"}}',
  375. $restrictions = @json_decode($field['xsdRestrictions'], $assoc = true);
  376. if (!empty($restrictions)) {
  377. if (!empty($restrictions['enumeration'])) {
  378. $sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` in (" . implode(",", array_map(function ($option) use ($charset) {
  379. return ($charset && $charset !== 'utf8')
  380. ? "CONVERT(" . DB::getPDO()->quote($option) . " using {$charset})"
  381. : DB::getPDO()->quote($option);
  382. }, array_keys($restrictions['enumeration']))) . ")";
  383. }
  384. }
  385. return $sqlRestrictions;
  386. }, $childLocalFieldsWithRestrictions),
  387. function ($ret, $cur) {
  388. return array_merge($ret, array_filter($cur, ['V', 'filterNotEmpty']));
  389. },
  390. $sqlWhereFromRestrictions
  391. );
  392. }
  393. }
  394. $sqlWhereFromRestrictions = (!empty($sqlWhereFromRestrictions)) ? implode("\n\t and ", $sqlWhereFromRestrictions) : "1=1";
  395. $sqlChildFieldName = $childAcl->getSqlFieldName($appInfoRootFieldName);
  396. $sql = "
  397. select root.{$rootPrimaryKeyField} as PRIMARY_KEY
  398. , child.{$childPrimaryKeyField} as REMOTE_PRIMARY_KEY
  399. , '' as REMOTE_TYPENAME
  400. , 'WAITING' as A_STATUS
  401. , 0 as TRANSACTION_ID
  402. , {$lastActionDateField} as A_LAST_ACTION_DATE
  403. from `{$rootTableName}` root
  404. join `{$childTableName}` child on(child.{$sqlChildFieldName} = root.{$appInfoChildFieldName})
  405. where {$sqlWhereFromRestrictions}
  406. ";
  407. DBG::log($sql, 'sql', "generateRefSelectSqlByFlatRelationCache");
  408. return $sql;
  409. }
  410. static function remove(Type_RefConfig $refConfig) {
  411. DB::getPDO()->update('CRM_REF_CONFIG', 'ID', $refConfig->id, [
  412. 'A_STATUS' => 'DELETED',
  413. 'A_LAST_ACTION_DATE' => 'NOW()',
  414. ]);
  415. }
  416. static function reactivate(Type_RefConfig $refConfig) {
  417. DB::getPDO()->update('CRM_REF_CONFIG', 'ID', $refConfig->id, [ // TODO: update ref table, update source -- fixed below by RefConfig::update
  418. 'A_STATUS' => 'WAITING',
  419. 'A_LAST_ACTION_DATE' => 'NOW()',
  420. ]);
  421. }
  422. static function getRefEventLogTable($objectNamespace, $childTypeName) {
  423. $refConfig = self::fetch($objectNamespace, $childTypeName);
  424. return "CRM__#REF_LOG__{$refConfig->id}";
  425. }
  426. static function installEventLogTable($objectNamespace, $childTypeName, Type_Field $newField, Type_RefConfig $refConfig = null) {
  427. // $refConfig->id
  428. // $refConfig->source
  429. // $refConfig->version
  430. // $refConfig->tableName
  431. $sqlLogTableName = self::getRefEventLogTable($objectNamespace, $childTypeName);
  432. DB::getPDO()->execSql("
  433. CREATE TABLE IF NOT EXISTS `{$sqlLogTableName}` (
  434. `PRIMARY_KEY` int(11) NOT NULL
  435. , `REMOTE_PRIMARY_KEY` int(11) NOT NULL
  436. , `REMOTE_TYPENAME` varchar(255) NOT NULL DEFAULT ''
  437. , `A_STATUS` enum('WAITING', 'NORMAL', 'DELETED') NOT NULL DEFAULT 'WAITING'
  438. , `TRANSACTION_ID` int(11) NOT NULL
  439. , `A_ACTION_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
  440. , KEY `PRIMARY_KEY` (`PRIMARY_KEY`)
  441. , KEY `REMOTE_PRIMARY_KEY` (`REMOTE_PRIMARY_KEY`)
  442. , KEY `TRANSACTION_ID` (`TRANSACTION_ID`)
  443. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 COMMENT='{$objectNamespace} #REF {$childTypeName}';
  444. ");
  445. }
  446. }