tripal_core.api.inc 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960
  1. <?php
  2. require_once "tripal_core.schema.api.inc";
  3. /**
  4. * @file
  5. * The Tripal Core API
  6. *
  7. * This file provides the API needed for all other Tripal and Tripal dependent
  8. * modules.
  9. *
  10. * @defgroup tripal_api Tripal API
  11. * @{
  12. * Provides an application programming interface (API) for Tripal
  13. *
  14. * The Tripal API currently provides generic insert/update/select functions for all chado content as
  15. * well as some module specific functions that insert/update/delete/select specific chado content.
  16. *
  17. * This API is currently in its infancy and some necessary functions might be missing. If you find
  18. * a missing function that you think should be included go to the sourceforge feature request
  19. * page and request it's inclusion in the API. Such feature requests with a working function
  20. * definition will be given priority.
  21. * @}
  22. *
  23. * @defgroup tripal_chado_api Core Module Chado API
  24. * @{
  25. * Provides an application programming interface (API) to manage data withing the Chado database.
  26. * This includes functions for selecting, inserting, updating and deleting records
  27. * in Chado tables. The functions will ensure proper integrity contraints are met
  28. * for inserts and updates.
  29. *
  30. * Also, a set of functions is provided for creating template variables. First,
  31. * is the tripal_core_generate_chado_vars which is used to select one ore more
  32. * records from a table and return an array with foreign key relationships fully
  33. * populated. For example, if selecting a feature, the organism_id and type_id
  34. * would be present in the returned array as a nested array with their respective
  35. * foreign keys also nested. The only fields that are not included are text
  36. * fields (which may be very large) or many-to-many foreign key relationships.
  37. * However, these fields and relationships can be expanded using the
  38. * tripal_core_expand_chado_vars.
  39. *
  40. * When a row from a chado table is selected using these two functions, it provides
  41. * a way for users who want to cutomize Drupal template files to access all data
  42. * associate with a specific record.
  43. *
  44. * Finally, the property tables in Chado generally follow the same format. Therefore
  45. * there is a set of functions for inserting, updating and deleting properties for
  46. * any table. This provides quick lookup of properties (provided the CV term is
  47. * known).
  48. *
  49. * @}
  50. * @ingroup tripal_api
  51. *
  52. * @defgroup tripal_files_api Core Module Files API
  53. * @{
  54. * Provides an application programming interface (API) for managing files within
  55. * the Tripal data directory structure.
  56. *
  57. * @}
  58. * @ingroup tripal_api
  59. /**
  60. * Provides a generic routine for inserting into any Chado table
  61. *
  62. * Use this function to insert a record into any Chado table. The first
  63. * argument specifies the table for inserting and the second is an array
  64. * of values to be inserted. The array is mutli-dimensional such that
  65. * foreign key lookup values can be specified.
  66. *
  67. * @param $table
  68. * The name of the chado table for inserting
  69. * @param $values
  70. * An associative array containing the values for inserting.
  71. *
  72. * @return
  73. * On success this function returns TRUE. On failure, it returns FALSE.
  74. *
  75. * Example usage:
  76. * @code
  77. * $values = array(
  78. * 'organism_id' => array(
  79. * 'genus' => 'Citrus',
  80. * 'species' => 'sinensis',
  81. * ),
  82. * 'name' => 'orange1.1g000034m.g',
  83. * 'uniquename' => 'orange1.1g000034m.g',
  84. * 'type_id' => array (
  85. * 'cv_id' => array (
  86. * 'name' => 'sequence',
  87. * ),
  88. * 'name' => 'gene',
  89. * 'is_obsolete' => 0
  90. * ),
  91. * );
  92. * $result = tripal_core_chado_insert('feature',$values);
  93. * @endcode
  94. * The above code inserts a record into the feature table. The $values array is
  95. * nested such that the organism is selected by way of the organism_id foreign
  96. * key constraint by specifying the genus and species. The cvterm is also
  97. * specified using its foreign key and the cv_id for the cvterm is nested as
  98. * well.
  99. *
  100. * @ingroup tripal_chado_api
  101. */
  102. function tripal_core_chado_insert($table, $values) {
  103. $insert_values = array();
  104. // get the table description
  105. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  106. if (empty($table_desc)) {
  107. watchdog('tripal_core', 'tripal_core_chado_insert: There is no table description for !table_name', array('!table_name' => $table), WATCHDOG_WARNING);
  108. }
  109. // iterate through the values array and create a new 'insert_values' array
  110. // that has all the values needed for insert with all foreign relationsihps
  111. // resolved.
  112. foreach ($values as $field => $value) {
  113. if (is_array($value)) {
  114. // select the value from the foreign key relationship for this value
  115. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
  116. if (sizeof($results) > 1) {
  117. watchdog('tripal_core', 'tripal_core_chado_insert: Too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)), WATCHDOG_ERROR);
  118. }
  119. elseif (sizeof($results) < 1) {
  120. //watchdog('tripal_core', 'tripal_core_chado_insert: no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)), WATCHDOG_ERROR);
  121. }
  122. else {
  123. $insert_values[$field] = $results[0];
  124. }
  125. }
  126. else {
  127. $insert_values[$field] = $value;
  128. }
  129. }
  130. // check for violation of any unique constraints
  131. $ukeys = $table_desc['unique keys'];
  132. $ukselect_cols = array();
  133. $ukselect_vals = array();
  134. if ($ukeys) {
  135. foreach ($ukeys as $name => $fields) {
  136. foreach ($fields as $index => $field) {
  137. // build the arrays for performing a select that will check the contraint
  138. array_push($ukselect_cols, $field);
  139. $ukselect_vals[$field] = $insert_values[$field];
  140. }
  141. // now check the constraint
  142. if (tripal_core_chado_select($table, $ukselect_cols, $ukselect_vals)) {
  143. watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert duplicate record into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  144. return FALSE;
  145. }
  146. }
  147. }
  148. // if trying to insert a field that is the primary key, make sure it also is unique
  149. $pkey = $table_desc['primary key'][0];
  150. if ($insert_values[$pkey]) {
  151. if (tripal_core_chado_select($table, array($pkey), array($pkey => $insert_values[$pkey]))) {
  152. watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert duplicate primary key into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  153. return FALSE;
  154. }
  155. }
  156. // make sure required fields have a value
  157. $fields = $table_desc['fields'];
  158. if (!is_array($fields)) {
  159. $fields = array();
  160. watchdog('tripal_core', "tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
  161. }
  162. foreach ($fields as $field => $def) {
  163. // a field is considered missing if it cannot be NULL and there is no default
  164. // value for it or it is of type 'serial'
  165. if ($def['not NULL'] == 1 and !array_key_exists($field, $insert_values) and !isset($def['default']) and strcmp($def['type'], serial) != 0) {
  166. watchdog('tripal_core', "tripal_core_chado_insert: Field $table.$field cannot be NULL: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  167. return FALSE;
  168. }
  169. }
  170. // Now build the insert SQL statement
  171. $ifields = array();
  172. $ivalues = array();
  173. $itypes = array();
  174. foreach ($insert_values as $field => $value) {
  175. array_push($ifields, $field);
  176. array_push($ivalues, $value);
  177. if (strcmp($value, '__NULL__') == 0) {
  178. array_push($itypes, "NULL");
  179. }
  180. elseif (strcmp($fields[$field]['type'], 'serial') == 0 or
  181. strcmp($fields[$field]['type'], 'int') == 0) {
  182. array_push($itypes, "%d");
  183. }
  184. else {
  185. array_push($itypes, "'%s'");
  186. }
  187. }
  188. $sql = "INSERT INTO {$table} (" . implode(", ", $ifields) . ") VALUES (". implode(", ", $itypes) .")";
  189. // finally perform the insert.
  190. $previous_db = tripal_db_set_active('chado'); // use chado database
  191. $result = db_query($sql, $ivalues);
  192. tripal_db_set_active($previous_db); // now use drupal database
  193. if ($result) {
  194. // add primary keys to values before return
  195. $primary_key = array();
  196. if (!is_array($table_desc['primary key'])) {
  197. $table_desc['primary key'] = array();
  198. watchdog('tripal_core', "tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
  199. }
  200. foreach ($table_desc['primary key'] as $field) {
  201. $value = db_last_insert_id($table, $field);
  202. $values[$field] = $value;
  203. }
  204. return $values;
  205. }
  206. else {
  207. watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert record into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  208. return FALSE;
  209. }
  210. return FALSE;
  211. }
  212. /**
  213. * Provides a generic function for deleting a record(s) from any chado table
  214. *
  215. * Use this function to delete a record(s) in any Chado table. The first
  216. * argument specifies the table to delete from and the second is an array
  217. * of values to match for locating the record(s) to be deleted. The arrays
  218. * are mutli-dimensional such that foreign key lookup values can be specified.
  219. *
  220. * @param $table
  221. * The name of the chado table for inserting
  222. * @param $match
  223. * An associative array containing the values for locating a record to update.
  224. *
  225. * @return
  226. * On success this function returns TRUE. On failure, it returns FALSE.
  227. *
  228. * Example usage:
  229. * @code
  230. $umatch = array(
  231. 'organism_id' => array(
  232. 'genus' => 'Citrus',
  233. 'species' => 'sinensis',
  234. ),
  235. 'uniquename' => 'orange1.1g000034m.g7',
  236. 'type_id' => array (
  237. 'cv_id' => array (
  238. 'name' => 'sequence',
  239. ),
  240. 'name' => 'gene',
  241. 'is_obsolete' => 0
  242. ),
  243. );
  244. $uvalues = array(
  245. 'name' => 'orange1.1g000034m.g',
  246. 'type_id' => array (
  247. 'cv_id' => array (
  248. 'name' => 'sequence',
  249. ),
  250. 'name' => 'mRNA',
  251. 'is_obsolete' => 0
  252. ),
  253. );
  254. * $result = tripal_core_chado_update('feature',$umatch,$uvalues);
  255. * @endcode
  256. * The above code species that a feature with a given uniquename, organism_id,
  257. * and type_id (the unique constraint for the feature table) will be deleted.
  258. * The organism_id is specified as a nested array that uses the organism_id
  259. * foreign key constraint to lookup the specified values to find the exact
  260. * organism_id. The same nested struture is also used for specifying the
  261. * values to update. The function will find all records that match the
  262. * columns specified and delete them.
  263. *
  264. * @ingroup tripal_chado_api
  265. */
  266. function tripal_core_chado_delete($table, $match) {
  267. $delete_matches = array(); // contains the values for the where clause
  268. // get the table description
  269. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  270. // get the values needed for matching in the SQL statement
  271. foreach ($match as $field => $value) {
  272. if (is_array($value)) {
  273. // if the user has specified an array of values to delete rather than
  274. // FK relationships the keep those in our match
  275. if (array_values($value) === $value) {
  276. $delete_matches[$field] = $value;
  277. }
  278. else {
  279. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
  280. if (sizeof($results) > 1) {
  281. watchdog('tripal_core', 'tripal_core_chado_delete: When trying to find record to delete, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)), WATCHDOG_ERROR);
  282. }
  283. elseif (sizeof($results) < 1) {
  284. //watchdog('tripal_core', 'tripal_core_chado_delete: When trying to find record to delete, no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value,TRUE)), WATCHDOG_ERROR);
  285. }
  286. else {
  287. $delete_matches[$field] = $results[0];
  288. }
  289. }
  290. }
  291. else {
  292. $delete_matches[$field] = $value;
  293. }
  294. }
  295. // now build the SQL statement
  296. $sql = "DELETE FROM {$table} WHERE ";
  297. $dargs = array();
  298. foreach ($delete_matches as $field => $value) {
  299. if (count($value) > 1) {
  300. $sql .= "$field IN (" . db_placeholders($value, 'varchar') . ") AND ";
  301. foreach ($value as $v) {
  302. $dargs[] = $v;
  303. }
  304. }
  305. else {
  306. if (strcmp($value, '__NULL__') == 0) {
  307. $sql .= " $field = NULL AND ";
  308. }
  309. elseif (strcmp($fields[$field]['type'], 'serial') == 0 or
  310. strcmp($fields[$field]['type'], 'int') == 0) {
  311. $sql .= " $field = %d AND ";
  312. }
  313. else {
  314. $sql .= " $field = '%s' AND ";
  315. }
  316. array_push($dargs, $value);
  317. }
  318. }
  319. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND'
  320. // finally perform the delete. If successful, return the updated record
  321. $previous_db = tripal_db_set_active('chado'); // use chado database
  322. $result = db_query($sql, $dargs);
  323. tripal_db_set_active($previous_db); // now use drupal database
  324. if ($result) {
  325. return TRUE;
  326. }
  327. else {
  328. watchdog('tripal_core', "Cannot delete record in $table table. Match:" . print_r($match, 1) . ". Values: ". print_r($values, 1), array(), 'WATCHDOG_ERROR');
  329. return FALSE;
  330. }
  331. return FALSE;
  332. }
  333. /**
  334. * Provides a generic routine for updating into any Chado table
  335. *
  336. * Use this function to update a record in any Chado table. The first
  337. * argument specifies the table for inserting, the second is an array
  338. * of values to matched for locating the record for updating, and the third
  339. * argument give the values to update. The arrays are mutli-dimensional such
  340. * that foreign key lookup values can be specified.
  341. *
  342. * @param $table
  343. * The name of the chado table for inserting
  344. * @param $match
  345. * An associative array containing the values for locating a record to update.
  346. * @param $values
  347. * An associative array containing the values for updating.
  348. *
  349. * @return
  350. * On success this function returns TRUE. On failure, it returns FALSE.
  351. *
  352. * Example usage:
  353. * @code
  354. $umatch = array(
  355. 'organism_id' => array(
  356. 'genus' => 'Citrus',
  357. 'species' => 'sinensis',
  358. ),
  359. 'uniquename' => 'orange1.1g000034m.g7',
  360. 'type_id' => array (
  361. 'cv_id' => array (
  362. 'name' => 'sequence',
  363. ),
  364. 'name' => 'gene',
  365. 'is_obsolete' => 0
  366. ),
  367. );
  368. $uvalues = array(
  369. 'name' => 'orange1.1g000034m.g',
  370. 'type_id' => array (
  371. 'cv_id' => array (
  372. 'name' => 'sequence',
  373. ),
  374. 'name' => 'mRNA',
  375. 'is_obsolete' => 0
  376. ),
  377. );
  378. * $result = tripal_core_chado_update('feature',$umatch,$uvalues);
  379. * @endcode
  380. * The above code species that a feature with a given uniquename, organism_id,
  381. * and type_id (the unique constraint for the feature table) will be updated.
  382. * The organism_id is specified as a nested array that uses the organism_id
  383. * foreign key constraint to lookup the specified values to find the exact
  384. * organism_id. The same nested struture is also used for specifying the
  385. * values to update. The function will find the record that matches the
  386. * columns specified and update the record with the avlues in the $uvalues array.
  387. *
  388. * @ingroup tripal_chado_api
  389. */
  390. function tripal_core_chado_update($table, $match, $values) {
  391. $update_values = array(); // contains the values to be updated
  392. $update_matches = array(); // contains the values for the where clause
  393. // get the table description
  394. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  395. // get the values needed for matching in the SQL statement
  396. foreach ($match as $field => $value) {
  397. if (is_array($value)) {
  398. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
  399. if (sizeof($results) > 1) {
  400. watchdog('tripal_core', 'tripal_core_chado_update: When trying to find record to update, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)), WATCHDOG_ERROR);
  401. }
  402. elseif (sizeof($results) < 1) {
  403. //watchdog('tripal_core', 'tripal_core_chado_update: When trying to find record to update, no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)), WATCHDOG_ERROR);
  404. }
  405. else {
  406. $update_matches[$field] = $results[0];
  407. }
  408. }
  409. else {
  410. $update_matches[$field] = $value;
  411. }
  412. }
  413. // get the values used for updating
  414. foreach ($values as $field => $value) {
  415. if (is_array($value)) {
  416. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
  417. if (sizeof($results) > 1) {
  418. watchdog('tripal_core', 'tripal_core_chado_update: When trying to find update values, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)), WATCHDOG_ERROR);
  419. }
  420. elseif (sizeof($results) < 1) {
  421. //watchdog('tripal_core', 'tripal_core_chado_update: When trying to find update values, no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value,TRUE)), WATCHDOG_ERROR);
  422. }
  423. else {
  424. $update_values[$field] = $results[0];
  425. }
  426. }
  427. else {
  428. $update_values[$field] = $value;
  429. }
  430. }
  431. // now build the SQL statement
  432. $sql = "UPDATE {$table} SET ";
  433. $fields = $table_desc['fields'];
  434. $uargs = array();
  435. foreach ($update_values as $field => $value) {
  436. if (strcmp($value, '__NULL__') == 0) {
  437. $sql .= " $field = NULL, ";
  438. }
  439. elseif (strcmp($fields[$field]['type'], 'serial')==0 or
  440. strcmp($fields[$field]['type'], 'int')==0) {
  441. $sql .= " $field = %d, ";
  442. }
  443. else {
  444. $sql .= " $field = '%s', ";
  445. }
  446. array_push($uargs, $value);
  447. }
  448. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing comma & space
  449. $sql .= " WHERE ";
  450. foreach ($update_matches as $field => $value) {
  451. if (strcmp($value, '__NULL__')==0) {
  452. $sql .= " $field = NULL AND ";
  453. }
  454. elseif (strcmp($fields[$field]['type'], 'serial')==0 or
  455. strcmp($fields[$field]['type'], 'int')==0) {
  456. $sql .= " $field = %d AND ";
  457. }
  458. else {
  459. $sql .= " $field = '%s' AND ";
  460. }
  461. array_push($uargs, $value);
  462. }
  463. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND'
  464. // finally perform the update. If successful, return the updated record
  465. $previous_db = tripal_db_set_active('chado'); // use chado database
  466. $result = db_query($sql, $uargs);
  467. tripal_db_set_active($previous_db); // now use drupal database
  468. if ($result) {
  469. return TRUE;
  470. }
  471. else {
  472. watchdog('tripal_core', "Cannot update record in $table table. Match:" . print_r($match, 1) . ". Values: ". print_r($values, 1), array(), 'WATCHDOG_ERROR');
  473. return FALSE;
  474. }
  475. return FALSE;
  476. }
  477. /**
  478. * Provides a generic routine for selecting data from a Chado table
  479. *
  480. * Use this function to perform a simple select from any Chado table.
  481. *
  482. * @param $table
  483. * The name of the chado table for inserting
  484. * @param $columns
  485. * An array of column names
  486. * @param $values
  487. * An associative array containing the values for filtering the results. In the
  488. * case where multiple values for the same time are to be selected an additional
  489. * entry for the field should appear for each value
  490. * @param $options
  491. * An associative array of additional options where the key is the option
  492. * and the value is the value of that option.
  493. *
  494. * Additional Options Include:
  495. * - has_record
  496. * Set this argument to 'TRUE' to have this function return a numeric
  497. * value for the number of recrods rather than the array of records. this
  498. * can be useful in 'if' statements to check the presence of particula records.
  499. * - return_sql
  500. * Set this to 'TRUE' to have this function return an array where the first
  501. * element is the sql that would have been run and the second is an array of
  502. * arguments.
  503. * - case_insensitive_columns
  504. * An array of columns to do a case insensitive search on.
  505. * - regex_columns
  506. * An array of columns where the value passed in should be treated as a regular expression
  507. * - order_by
  508. * An associative array containing the column names of the table as keys
  509. * and the type of sort (i.e. ASC, DESC) as the values. The results in the
  510. * query will be sorted by the key values in the direction listed by the value
  511. *
  512. * @return
  513. * A database query result resource, FALSE if the query was not executed
  514. * correctly, or the number of records in the dataset if $has_record is set.
  515. *
  516. * Example usage:
  517. * @code
  518. * $columns = array('feature_id', 'name');
  519. * $values = array(
  520. * 'organism_id' => array(
  521. * 'genus' => 'Citrus',
  522. * 'species' => array('sinensis', 'clementina'),
  523. * ),
  524. * 'uniquename' => 'orange1.1g000034m.g',
  525. * 'type_id' => array (
  526. * 'cv_id' => array (
  527. * 'name' => 'sequence',
  528. * ),
  529. * 'name' => 'gene',
  530. * 'is_obsolete' => 0
  531. * ),
  532. * );
  533. * $result = tripal_core_chado_select('feature',$columns,$values);
  534. * @endcode
  535. * The above code selects a record from the feature table using the three fields
  536. * that uniquely identify a feature. The $columns array simply lists the columns
  537. * to select. The $values array is nested such that the organism is identified by
  538. * way of the organism_id foreign key constraint by specifying the genus and
  539. * species. The cvterm is also specified using its foreign key and the cv_id
  540. * for the cvterm is nested as well. In the example above, two different species
  541. * are allowed to match
  542. *
  543. * @ingroup tripal_chado_api
  544. */
  545. function tripal_core_chado_select($table, $columns, $values, $options = NULL) {
  546. if (!is_array($options)) {
  547. $options = array();
  548. }
  549. if (!$options['case_insensitive_columns']) {
  550. $options['case_insensitive_columns'] = array();
  551. }
  552. if (!$options['regex_columns']) {
  553. $options['regex_columns'] = array();
  554. }
  555. if (!$options['order_by']) {
  556. $options['order_by'] = array();
  557. }
  558. if (!is_array($columns)) {
  559. watchdog('tripal_core', 'the $columns argument for tripal_core_chado_select must be an array.');
  560. return FALSE;
  561. }
  562. if (!is_array($values)) {
  563. watchdog('tripal_core', 'the $values argument for tripal_core_chado_select must be an array.');
  564. return FALSE;
  565. }
  566. // get the table description
  567. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  568. $select = '';
  569. $from = '';
  570. $where = '';
  571. $args = array();
  572. foreach ($values as $field => $value) {
  573. $select[] = $field;
  574. if (is_array($value)) {
  575. // if the user has specified multiple values for matching then this we
  576. // want to catch that and save them in our $where array, otherwise
  577. // we'll descend for a foreign key relationship
  578. if (array_values($value) === $value) {
  579. $where[$field] = $value;
  580. }
  581. else {
  582. // select the value from the foreign key relationship for this value
  583. $foreign_options = array(
  584. 'regex_columns' => $options['regex_columns'],
  585. 'case_insensitive_columns' => $options['case_insensitive_columns']
  586. );
  587. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
  588. if (count($results) ==0) {
  589. // foreign key records are required
  590. // thus if none matched then return FALSE and alert the admin through watchdog
  591. //watchdog('tripal_core',
  592. // 'tripal_core_chado_select: no record in the table referenced by the foreign key (!field) exists. tripal_core_chado_select table=!table, columns=!columns, values=!values',
  593. // array('!table' => $table,
  594. // '!columns' => '<pre>' . print_r($columns, TRUE) . '</pre>',
  595. // '!values' => '<pre>' . print_r($values, TRUE) . '</pre>',
  596. // '!field' => $field,
  597. // ),
  598. // WATCHDOG_WARNING);
  599. return FALSE;
  600. }
  601. else {
  602. $where[$field] = $results;
  603. }
  604. }
  605. }
  606. else {
  607. //need to catch a 0 and make int if integer field
  608. if ($table_desc['fields'][$field]['type'] == 'int') {
  609. $where[$field][] = (int) $value;
  610. }
  611. else {
  612. $where[$field][] = $value;
  613. }
  614. }
  615. }
  616. // now build the SQL select statement
  617. if (empty($where)) {
  618. // sometimes want to select everything
  619. $sql = "SELECT " . implode(', ', $columns) . " ";
  620. $sql .= "FROM {$table} ";
  621. }
  622. else {
  623. $sql = "SELECT " . implode(', ', $columns) . " ";
  624. $sql .= "FROM {$table} ";
  625. $sql .= "WHERE ";
  626. foreach ($where as $field => $value) {
  627. if (count($value) > 1) {
  628. $sql .= "$field IN (" . db_placeholders($value, 'varchar') . ") AND ";
  629. foreach ($value as $v) {
  630. $args[] = $v;
  631. }
  632. }
  633. else {
  634. $operator = '=';
  635. if (in_array($field, $options['regex_columns'])) {
  636. $operator = '~*';
  637. }
  638. if (in_array($field, $options['case_insensitive_columns'])) {
  639. $sql .= "lower($field) $operator lower('%s') AND ";
  640. $args[] = $value[0];
  641. }
  642. else {
  643. $sql .= "$field $operator '%s' AND ";
  644. $args[] = $value[0];
  645. }
  646. }
  647. }
  648. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND '
  649. }
  650. // finally add any ordering of the results to the SQL statement
  651. if (count($options['order_by']) > 0) {
  652. $sql .= " ORDER BY ";
  653. foreach ($options['order_by'] as $field => $dir) {
  654. $sql .= "$field $dir, ";
  655. }
  656. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing ', '
  657. }
  658. // if the caller has requested the SQL rather than the results...
  659. // which happens in the case of wanting to use the Drupal pager, then do so
  660. if ($options['return_sql']) {
  661. return array('sql' => $sql, 'args' => $args);
  662. }
  663. $previous_db = tripal_db_set_active('chado'); // use chado database
  664. $resource = db_query($sql, $args);
  665. tripal_db_set_active($previous_db); // now use drupal database
  666. $results = array();
  667. while ($r = db_fetch_object($resource)) {
  668. $results[] = $r;
  669. }
  670. if (!$options['has_record']) {
  671. return $results;
  672. }
  673. else {
  674. return count($results);
  675. }
  676. }
  677. /**
  678. * Gets the value of a foreign key relationship
  679. *
  680. * This function is used by tripal_core_chado_select, tripal_core_chado_insert,
  681. * and tripal_core_chado_update to iterate through the associate array of
  682. * values that gets passed to each of those routines. The values array
  683. * is nested where foreign key contraints are used to specify a value that. See
  684. * documentation for any of those functions for further information.
  685. *
  686. * @param $table_desc
  687. * A table description for the table with the foreign key relationship to be identified generated by
  688. * hook_chado_<table name>_schema()
  689. * @param $field
  690. * The field in the table that is the foreign key.
  691. * @param $values
  692. * An associative array containing the values
  693. * @param $options
  694. * An associative array of additional options where the key is the option
  695. * and the value is the value of that option. These options are passed on to tripal_core_chado_select.
  696. *
  697. * Additional Options Include:
  698. * - case_insensitive_columns
  699. * An array of columns to do a case insensitive search on.
  700. * - regex_columns
  701. * An array of columns where the value passed in should be treated as a regular expression
  702. *
  703. * @return
  704. * A string containg the results of the foreign key lookup, or FALSE if failed.
  705. *
  706. * Example usage:
  707. * @code
  708. *
  709. * $values = array(
  710. * 'genus' => 'Citrus',
  711. * 'species' => 'sinensis',
  712. * );
  713. * $value = tripal_core_chado_get_foreign_key('feature', 'organism_id',$values);
  714. *
  715. * @endcode
  716. * The above code selects a record from the feature table using the three fields
  717. * that uniquely identify a feature. The $columns array simply lists the columns
  718. * to select. The $values array is nested such that the organism is identified by
  719. * way of the organism_id foreign key constraint by specifying the genus and
  720. * species. The cvterm is also specified using its foreign key and the cv_id
  721. * for the cvterm is nested as well.
  722. *
  723. * @ingroup tripal_chado_api
  724. */
  725. function tripal_core_chado_get_foreign_key($table_desc, $field, $values, $options = NULL) {
  726. if (!is_array($options)) {
  727. $options = array();
  728. }
  729. if (!$options['case_insensitive_columns']) {
  730. $options['case_insensitive_columns'] = array();
  731. }
  732. if (!$options['regex_columns']) {
  733. $options['regex_columns'] = array();
  734. }
  735. // get the list of foreign keys for this table description and
  736. // iterate through those until we find the one we're looking for
  737. $fkeys = $table_desc['foreign keys'];
  738. if ($fkeys) {
  739. foreach ($fkeys as $name => $def) {
  740. if (is_array($def['table'])) {
  741. //foreign key was described 2X
  742. $message = "The foreign key " . $name . " was defined twice. Please check modules "
  743. ."to determine if hook_chado_" . $table_desc['table'] . "_schema() was "
  744. ."implemented and defined this foreign key when it wasn't supposed to. Modules "
  745. ."this hook was implemented in: " . implode(', ',
  746. module_implements("chado_" . $table_desc['table'] . "_schema")) . ".";
  747. watchdog('tripal_core', $message);
  748. drupal_set_message(check_plain($message), 'error');
  749. continue;
  750. }
  751. $table = $def['table'];
  752. $columns = $def['columns'];
  753. // iterate through the columns of the foreign key relationship
  754. foreach ($columns as $left => $right) {
  755. // does the left column in the relationship match our field?
  756. if (strcmp($field, $left) == 0) {
  757. // the column name of the foreign key matches the field we want
  758. // so this is the right relationship. Now we want to select
  759. $select_cols = array($right);
  760. $result = tripal_core_chado_select($table, $select_cols, $values, $options);
  761. $fields = array();
  762. if (count($result) > 0) {
  763. foreach ($result as $obj) {
  764. $fields[] = $obj->$right;
  765. }
  766. return $fields;
  767. }
  768. }
  769. }
  770. }
  771. }
  772. else {
  773. // TODO: what do we do if we get to this point and we have a fk
  774. // relationship expected but we don't have any definition for one in the
  775. // table schema??
  776. $message = "There is no foreign key relationship defined for " . $field . ".
  777. To define a foreign key relationship, determine the table this foreign
  778. key referrs to (<foreign table>) and then implement
  779. hook_chado_<foreign table>_schema(). See
  780. tripal_feature_chado_feature_schema for an example.";
  781. watchdog('tripal_core', $message);
  782. drupal_set_message(check_plain($message), 'error');
  783. }
  784. return FALSE;
  785. }
  786. /**
  787. * Generates an object containing the full details of a record(s) in chado.
  788. *
  789. * This differs from the objects returned by tripal_core_chado_select in so far as all foreign key
  790. * relationships have been followed meaning you have more complete details. Thus this function
  791. * should be used whenever you need a full variable and tripal_core_chado_select should be used if
  792. * you only case about a few columns.
  793. *
  794. * @param $table
  795. * The name of the base table to generate a variable for
  796. * @param $values
  797. * A select values array that selects the records you want from the base table
  798. * (this has the same form as tripal_core_chado_select)
  799. * @param $base_options
  800. * An array containing options for the base table. For example, an
  801. * option of 'order_by' may be used to sort results in the base table
  802. * if more than one are returned. The options must be compatible with
  803. * the options accepted by the tripal_core_chado_select() function.
  804. * @return
  805. * Either an object (if only one record was selected from the base table)
  806. * or an array of objects (if more than one record was selected from the base table).
  807. *
  808. * Example Usage:
  809. * @code
  810. $values = array(
  811. 'name' => 'Medtr4g030710'
  812. );
  813. $features = tripal_core_generate_chado_var('feature', $values);
  814. * @endcode
  815. * This will return an object if there is only one feature with the name Medtr4g030710 or it will
  816. * return an array of feature objects if more than one feature has that name.
  817. *
  818. * Note to Module Designers: Fields can be excluded by default from these objects by implementing
  819. * one of the following hooks:
  820. * - hook_exclude_field_from_tablename_by_default (where tablename is the name of the table):
  821. * This hook allows you to add fields to be excluded on a per table basis. Simply implement
  822. * this hook to return an array of fields to be excluded. For example:
  823. * @code
  824. mymodule_exclude_field_from_feature_by_default() {
  825. return array('residues' => TRUE);
  826. }
  827. * @endcode
  828. * will ensure that feature.residues is ecluded from a feature object by default.
  829. * - hook_exclude_type_by_default:
  830. * This hook allows you to exclude fields from all tables that are of a given postgresql field
  831. * type. Simply implement this hook to return an array of postgresql types mapped to criteria.
  832. * Then all fields of that type where the criteria supplied returns TRUE will be excluded from
  833. * any table. Tokens available in criteria are &gt;field_value&lt; and &gt;field_name&lt; . For example:
  834. * @code
  835. mymodule_exclude_type_by_default() {
  836. return array('text' => 'length(&gt;field_value&lt; ) > 50');
  837. }
  838. * @endcode
  839. * will exclude all text fields with a length > 50. Thus if $feature.residues is longer than 50 * it will be excluded, otherwise it will be added.
  840. *
  841. * @ingroup tripal_chado_api
  842. */
  843. function tripal_core_generate_chado_var($table, $values, $base_options = array()) {
  844. $all = new stdClass();
  845. // get description for the current table----------------------------------------------------------
  846. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  847. $table_primary_key = $table_desc['primary key'][0];
  848. $table_columns = array_keys($table_desc['fields']);
  849. // Expandable fields without value needed for criteria--------------------------------------------
  850. $all->expandable_fields = array();
  851. if ($table_desc['referring_tables']) {
  852. $all->expandable_tables = $table_desc['referring_tables'];
  853. }
  854. else {
  855. $all->expandable_tables = array();
  856. }
  857. $all->expandable_nodes = array();
  858. // Get fields to be removed by name.................................
  859. $fields_to_remove = module_invoke_all('exclude_field_from_' . $table . '_by_default');
  860. foreach ($fields_to_remove as $field_name => $criteria) {
  861. //replace &gt;field_name&lt; with the current field name &
  862. $criteria = preg_replace('/&gt;field_name&lt; /', $field_name, $criteria);
  863. // if field_value needed we can't deal with this field yet
  864. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  865. break;
  866. }
  867. //if criteria then remove from query
  868. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  869. // watchdog('tripal_core',
  870. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  871. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  872. // WATCHDOG_NOTICE
  873. // );
  874. if ($success) {
  875. unset($table_columns[array_search($field_name, $table_columns)]);
  876. unset($fields_to_remove[$field_name]);
  877. $all->expandable_fields[] = $table . '.' . $field_name;
  878. }
  879. }
  880. //Get fields to be removed by type................................
  881. $types_to_remove = module_invoke_all('exclude_type_by_default');
  882. $field_types = array();
  883. foreach ($table_desc['fields'] as $field_name => $field_array) {
  884. $field_types[$field_array['type']][] = $field_name;
  885. }
  886. foreach ($types_to_remove as $field_type => $criteria) {
  887. // if there are fields of that type to remove
  888. if (is_array($field_types[$field_type])) {
  889. //replace &gt;field_name&lt; with the current field name &
  890. $criteria = preg_replace('/&gt;field_name&lt; /', $field_name, $criteria);
  891. foreach ($field_types[$field_type] as $field_name) {
  892. // if field_value needed we can't deal with this field yet
  893. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  894. $fields_to_remove[$field_name] = $criteria;
  895. continue;
  896. }
  897. // if field_value needed we can't deal with this field yet
  898. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  899. break;
  900. }
  901. //if criteria then remove from query
  902. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  903. // watchdog('tripal_core',
  904. // 'Evaluating criteria (%criteria) for field %field of $type in tripal_core_generate_chado_var for %table evaluated to %success',
  905. // array('%table'=>$table, '%criteria'=>$criteria, '%field'=>$field_name, '%type'=>$field_type, '%success'=>$success),
  906. // WATCHDOG_NOTICE
  907. // );
  908. if ($success) {
  909. unset($table_columns[array_search($field_name, $table_columns)]);
  910. $all->expandable_fields[] = $table . '.' . $field_name;
  911. }
  912. } //end of foreach field of that type
  913. }
  914. } //end of foreach type to be removed
  915. // get the values for the record in the current table---------------------------------------------
  916. $results = tripal_core_chado_select($table, $table_columns, $values, $base_options);
  917. if ($results) {
  918. foreach ($results as $key => $object) {
  919. // Add empty expandable_x arrays
  920. $object->expandable_fields = $all->expandable_fields;
  921. $object->expandable_tables = $all->expandable_tables;
  922. $object->expandable_nodes = $all->expandable_nodes;
  923. // add curent table
  924. $object->tablename = $table;
  925. // check if the current table maps to a node type-----------------------------------------------
  926. // if this table is connected to a node there will be a chado_tablename table in drupal
  927. if (db_table_exists('chado_' . $table)) {
  928. // that has a foreign key to this one ($table_desc['primary key'][0]
  929. // and to the node table (nid)
  930. $sql = "SELECT %s, nid FROM chado_%s WHERE %s=%d";
  931. $mapping = db_fetch_object(db_query(
  932. $sql,
  933. $table_primary_key,
  934. $table,
  935. $table_primary_key,
  936. $object->{$table_primary_key}
  937. ));
  938. if ($mapping->{$table_primary_key}) {
  939. $object->nid = $mapping->nid;
  940. $object->expandable_nodes[] = $table;
  941. }
  942. }
  943. // remove any fields where criteria need to be evalulated---------------------------------------
  944. foreach ($fields_to_remove as $field_name => $criteria) {
  945. if (!isset($object->{$field_name})) {
  946. break;
  947. }
  948. $criteria = preg_replace('/&gt;field_value&lt; /', $object->{$field_name}, $criteria);
  949. //if criteria then remove from query
  950. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  951. // watchdog('tripal_core',
  952. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  953. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  954. // WATCHDOG_NOTICE
  955. // );
  956. if ($success) {
  957. unset($object->{$field_name});
  958. $object->expandable_fields[] = $table . '.' . $field_name;
  959. }
  960. }
  961. // recursively follow foreign key relationships nesting objects as we go------------------------
  962. if ($table_desc['foreign keys']) {
  963. foreach ($table_desc['foreign keys'] as $foreign_key_array) {
  964. $foreign_table = $foreign_key_array['table'];
  965. foreach ($foreign_key_array['columns'] as $foreign_key => $primary_key) {
  966. // Note: Foreign key is the field in the current table whereas primary_key is the field in
  967. // the table referenced by the foreign key
  968. //Dont do anything if the foreign key is empty
  969. if (empty($object->{$foreign_key})) {
  970. break;
  971. }
  972. // get the record from the foreign table
  973. $foreign_values = array($primary_key => $object->{$foreign_key});
  974. $foreign_object = tripal_core_generate_chado_var($foreign_table, $foreign_values);
  975. // add the foreign record to the current object in a nested manner
  976. $object->{$foreign_key} = $foreign_object;
  977. // Flatten expandable_x arrays so only in the bottom object
  978. if (is_array($object->{$foreign_key}->expandable_fields)) {
  979. $object->expandable_fields = array_merge(
  980. $object->expandable_fields,
  981. $object->{$foreign_key}->expandable_fields
  982. );
  983. unset($object->{$foreign_key}->expandable_fields);
  984. }
  985. if (is_array($object->{$foreign_key}->expandable_tables)) {
  986. $object->expandable_tables = array_merge(
  987. $object->expandable_tables,
  988. $object->{$foreign_key}->expandable_tables
  989. );
  990. unset($object->{$foreign_key}->expandable_tables);
  991. }
  992. if (is_array($object->{$foreign_key}->expandable_nodes)) {
  993. $object->expandable_nodes = array_merge(
  994. $object->expandable_nodes,
  995. $object->{$foreign_key}->expandable_nodes
  996. );
  997. unset($object->{$foreign_key}->expandable_nodes);
  998. }
  999. }
  1000. }
  1001. $results[$key] = $object;
  1002. }
  1003. }
  1004. }
  1005. // check only one result returned
  1006. if (sizeof($results) == 1) {
  1007. // add results to object
  1008. return $results[0];
  1009. }
  1010. elseif (!empty($results)) {
  1011. return $results;
  1012. }
  1013. else {
  1014. // no results returned
  1015. }
  1016. }
  1017. /**
  1018. * Retrieves fields/tables/nodes that were excluded by default from a variable and adds them
  1019. *
  1020. * This function exists to allow tripal_core_generate_chado_var() to excldue some
  1021. * fields/tables/nodes from the default form of a variable without making it extremely difficult for
  1022. * the tripal admin to get at these variables if he/she wants them.
  1023. *
  1024. * @param $object
  1025. * This must be an object generated using tripal_core_generate_chado_var()
  1026. * @param $type
  1027. * Must be one of 'field', 'table', 'node'. Indicates what is being expanded.
  1028. * @param $to_expand
  1029. * The name of the field/table/node to be expanded
  1030. * @param $table_options
  1031. * An array containing options for the base table. For example, an
  1032. * option of 'order_by' may be used to sort results in the base table
  1033. * if more than one are returned. The options must be compatible with
  1034. * the options accepted by the tripal_core_chado_select() function.
  1035. * @return
  1036. * A chado object supplemented with the field/table/node requested to be expanded
  1037. *
  1038. * Example Usage:
  1039. * @code
  1040. // Get a chado object to be expanded
  1041. $values = array(
  1042. 'name' => 'Medtr4g030710'
  1043. );
  1044. $features = tripal_core_generate_chado_var('feature', $values);
  1045. // Expand the organism node
  1046. $feature = tripal_core_expand_chado_vars($feature, 'node', 'organism');
  1047. // Expand the feature.residues field
  1048. $feature = tripal_core_expand_chado_vars($feature, 'field', 'feature.residues');
  1049. // Expand the feature properties (featureprop table)
  1050. $feature = tripal_core_expand_chado_vars($feature, 'table', 'featureprop');
  1051. * @endcode
  1052. *
  1053. * @ingroup tripal_chado_api
  1054. */
  1055. function tripal_core_expand_chado_vars($object, $type, $to_expand, $table_options = array()) {
  1056. $base_table = $object->tablename;
  1057. // check to see if they are expanding an array of objects
  1058. if (is_array($object)) {
  1059. foreach ($object as $index => $o) {
  1060. $object[$index] = tripal_core_expand_chado_vars($o, $type, $to_expand);
  1061. }
  1062. return $object;
  1063. }
  1064. switch ($type) {
  1065. case "field": //--------------------------------------------------------------------------------
  1066. if (preg_match('/(\w+)\.(\w+)/', $to_expand, $matches)) {
  1067. $tablename = $matches[1];
  1068. $fieldname = $matches[2];
  1069. $table_desc = module_invoke_all('chado_' . $tablename . '_schema');
  1070. $values = array();
  1071. foreach ($table_desc['primary key'] as $key) {
  1072. $values[$key] = $object->{$key};
  1073. }
  1074. if ($base_table == $tablename) {
  1075. //get the field
  1076. $results = tripal_core_chado_select(
  1077. $tablename,
  1078. array($fieldname),
  1079. $values
  1080. );
  1081. $object->{$fieldname} = $results[0]->{$fieldname};
  1082. $object->expanded = $to_expand;
  1083. }
  1084. else {
  1085. //We need to recurse -the field is in a nested object
  1086. foreach ((array) $object as $field_name => $field_value) {
  1087. if (is_object($field_value)) {
  1088. $object->{$field_name} = tripal_core_expand_chado_vars(
  1089. $field_value,
  1090. 'field',
  1091. $to_expand
  1092. );
  1093. }
  1094. } //end of for each field in the current object
  1095. }
  1096. }
  1097. else {
  1098. watchdog(
  1099. 'tripal_core',
  1100. 'tripal_core_expand_chado_vars: Field (%field) not in the right format. It should be <tablename>.<fieldname>',
  1101. WATCHDOG_ERROR
  1102. );
  1103. }
  1104. break;
  1105. case "table": //--------------------------------------------------------------------------------
  1106. $foreign_table = $to_expand;
  1107. $foreign_table_desc = module_invoke_all('chado_' . $foreign_table . '_schema');
  1108. // If it's connected to the base table
  1109. if ($foreign_table_desc['foreign keys'][$base_table]) {
  1110. foreach ($foreign_table_desc['foreign keys'][$base_table]['columns'] as $left => $right) {
  1111. if (!$object->{$right}) {
  1112. break;
  1113. }
  1114. if (is_array($values)) {
  1115. $values = array_merge($values, array($left => $object->{$right}) );
  1116. }
  1117. else {
  1118. $values = array($left => $object->{$right});
  1119. }
  1120. $foreign_object = tripal_core_generate_chado_var(
  1121. $foreign_table,
  1122. array($left => $object->{$right}),
  1123. $table_options
  1124. );
  1125. if ($foreign_object) {
  1126. // in the case where the a foreign key relationships exists more
  1127. // than once with the same table we want to alter the
  1128. // array structure
  1129. if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
  1130. $object->{$foreign_table}->{$left} = $foreign_object;
  1131. $object->expanded = $to_expand;
  1132. }
  1133. else {
  1134. $object->{$foreign_table} = $foreign_object;
  1135. $object->expanded = $to_expand;
  1136. }
  1137. }
  1138. }
  1139. }
  1140. else {
  1141. //We need to recurse -the table has a relationship to one of the nested objects
  1142. foreach ((array) $object as $field_name => $field_value) {
  1143. // if we have a nested object ->expand the table in it
  1144. if (is_object($field_value)) {
  1145. $object->{$field_name} = tripal_core_expand_chado_vars(
  1146. $field_value,
  1147. 'table',
  1148. $foreign_table
  1149. );
  1150. }
  1151. }
  1152. }
  1153. break;
  1154. case "node": //---------------------------------------------------------------------------------
  1155. //if the node to be expanded is for our base table, then just expand it
  1156. if ($object->tablename == $to_expand) {
  1157. $node = node_load($object->nid);
  1158. if ($node) {
  1159. $object->expanded = $to_expand;
  1160. $node->expandable_fields = $object->expandable_fields;
  1161. unset($object->expandable_fields);
  1162. $node->expandable_tables = $object->expandable_tables;
  1163. unset($object->expandable_tables);
  1164. $node->expandable_nodes = $object->expandable_nodes;
  1165. unset($object->expandable_nodes);
  1166. $node->{$base_table} = $object;
  1167. $object = $node;
  1168. }
  1169. else {
  1170. watchdog(
  1171. 'tripal_core',
  1172. 'tripal_core_expand_chado_vars: No node matches the nid (%nid) supplied.',
  1173. array('%nid' => $object->nid),
  1174. WATCHDOG_ERROR
  1175. );
  1176. } //end of if node
  1177. }
  1178. else {
  1179. //We need to recurse -the node to expand is one of the nested objects
  1180. foreach ((array) $object as $field_name => $field_value) {
  1181. if (is_object($field_value)) {
  1182. $object->{$field_name} = tripal_core_expand_chado_vars(
  1183. $field_value,
  1184. 'node',
  1185. $to_expand
  1186. );
  1187. }
  1188. } //end of for each field in the current object
  1189. }
  1190. break;
  1191. default:
  1192. watchdog('tripal_core',
  1193. 'tripal_core_expand_chado_vars: Unrecognized type (%type). Should be one of "field", "table", "node".',
  1194. array('%type' => $type),
  1195. WATCHDOG_ERROR
  1196. );
  1197. return FALSE;
  1198. }
  1199. //move extended array downwards-------------------------------------------------------------------
  1200. if (!$object->expanded) {
  1201. //if there's no extended field then go hunting for it
  1202. foreach ( (array)$object as $field_name => $field_value) {
  1203. if (is_object($field_value)) {
  1204. if (isset($field_value->expanded)) {
  1205. $object->expanded = $field_value->expanded;
  1206. unset($field_value->expanded);
  1207. }
  1208. }
  1209. }
  1210. }
  1211. //try again becasue now we might have moved it down
  1212. if ($object->expanded) {
  1213. $expandable_name = 'expandable_' . $type . 's';
  1214. if ($object->{$expandable_name}) {
  1215. $key_to_remove = array_search($object->expanded, $object->{$expandable_name});
  1216. unset($object->{$expandable_name}[$key_to_remove]);
  1217. unset($object->expanded);
  1218. }
  1219. else {
  1220. // if there is an expandable array then we've reached the base object
  1221. // if we get here and don't have anything expanded then something went wrong
  1222. // watchdog(
  1223. // 'tripal_core',
  1224. // 'tripal_core_expand_chado_vars: Unable to expand the %type %to_expand',
  1225. // array('%type'=>$type, '%to_expand'=>$to_expand),
  1226. // WATCHDOG_ERROR
  1227. // );
  1228. } //end of it we've reached the base object
  1229. }
  1230. return $object;
  1231. }
  1232. /**
  1233. * Implements hook_exclude_type_by_default()
  1234. *
  1235. * This hooks allows fields of a specified type that match a specified criteria to be excluded by
  1236. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1237. * fields are excluded by default they can always be expanded at a later date using
  1238. * tripal_core_expand_chado_vars().
  1239. *
  1240. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1241. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1242. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1243. * contain the following tokens:
  1244. * - &gt;field_name&lt;
  1245. * Replaced by the name of the field to be excluded
  1246. * - &gt;field_value&lt;
  1247. * Replaced by the value of the field in the current record
  1248. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1249. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1250. * query.
  1251. *
  1252. * @return
  1253. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1254. *
  1255. * @ingroup tripal_chado_api
  1256. */
  1257. function tripal_core_exclude_type_by_default() {
  1258. return array('text' => "strlen('&gt;field_value&lt; ') > 100");
  1259. }
  1260. /**
  1261. * Implements hook_exclude_field_from_<tablename>_by_default()
  1262. *
  1263. * This hooks allows fields from a specified table that match a specified criteria to be excluded by
  1264. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1265. * fields are excluded by default they can always be expanded at a later date using
  1266. * tripal_core_expand_chado_vars().
  1267. *
  1268. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1269. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1270. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1271. * contain the following tokens:
  1272. * - &gt;field_name&lt;
  1273. * Replaced by the name of the field to be excluded
  1274. * - &gt;field_value&lt;
  1275. * Replaced by the value of the field in the current record
  1276. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1277. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1278. * query.
  1279. *
  1280. * @return
  1281. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1282. *
  1283. * @ingroup tripal_chado_api
  1284. */
  1285. function tripal_core_exclude_field_from_feature_by_default() {
  1286. return array();
  1287. }
  1288. /**
  1289. * Use this function instead of db_query() to avoid switching databases
  1290. * when making query to the chado database
  1291. */
  1292. function chado_query($sql) {
  1293. $args = func_get_args();
  1294. array_shift($args);
  1295. $sql = db_prefix_tables($sql);
  1296. if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
  1297. $args = $args[0];
  1298. }
  1299. _db_query_callback($args, TRUE);
  1300. $sql = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $sql);
  1301. $previous_db = tripal_db_set_active('chado');
  1302. $results = _db_query($sql);
  1303. tripal_db_set_active($previous_db);
  1304. return $results;
  1305. }
  1306. /**
  1307. * Get chado id for a node. E.g, if you want to get 'analysis_id' from the
  1308. * 'analysis' table for a synced 'chado_analysis' node, use:
  1309. * $analysis_id = chado_get_id_for_node ('analysis', $node)
  1310. * Likewise,
  1311. * $organism_id = chado_get_id_for_node ('organism', $node)
  1312. * $feature_id = chado_get_id_for_node ('feature', $node)
  1313. */
  1314. function chado_get_id_for_node($table, $node) {
  1315. return db_result(db_query("SELECT %s_id FROM {chado_%s} WHERE nid = %d", $table, $table, $node->nid));
  1316. }
  1317. /**
  1318. * Get node id for a chado feature/organism/analysis. E.g, if you want to
  1319. * get the node id for an analysis, use:
  1320. * $nid = chado_get_node_id ('analysis', $analysis_id)
  1321. * Likewise,
  1322. * $nid = chado_get_node_id ('organism', $organism_id)
  1323. * $nid = chado_get_node_id ('feature', $feature_id)
  1324. */
  1325. function chado_get_node_id($table, $id) {
  1326. return db_result(db_query("SELECT nid FROM {chado_%s} WHERE %s_id = %d", $table, $table, $id));
  1327. }
  1328. /**
  1329. * Retrieve a property for a given base table record
  1330. *
  1331. * @param $basetable
  1332. * The base table for which the property should be retrieved. Thus to retrieve a property
  1333. * for a feature the basetable=feature and property is retrieved from featureprop
  1334. * @param $record_id
  1335. * The foriegn key field of the base table. This should be in integer.
  1336. * @param $property
  1337. * The cvterm name describing the type of properties to be retrieved
  1338. * @param $cv_name
  1339. * The name of the cv that the above cvterm is part of
  1340. *
  1341. * @return
  1342. * An array in the same format as that generated by the function
  1343. * tripal_core_generate_chado_var(). If only one record is returned it
  1344. * is a single object. If more than one record is returned then it is an array
  1345. * of objects
  1346. *
  1347. * @ingroup tripal_chado_api
  1348. */
  1349. function tripal_core_get_property($basetable, $record_id, $property, $cv_name) {
  1350. // get the foreign key for this property table
  1351. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1352. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1353. // construct the array of values to be selected
  1354. $values = array(
  1355. $fkcol => $record_id,
  1356. 'type_id' => array(
  1357. 'cv_id' => array(
  1358. 'name' => $cv_name,
  1359. ),
  1360. 'name' => $property,
  1361. 'is_obsolete' => 0
  1362. ),
  1363. );
  1364. $results = tripal_core_generate_chado_var($basetable . 'prop', $values);
  1365. $results = tripal_core_expand_chado_vars($results, 'field', $basetable . 'prop.value');
  1366. return $results;
  1367. }
  1368. /**
  1369. * Insert a property for a given base table. By default if the property already
  1370. * exists a new property is added with the next available rank. If
  1371. * $update_if_present argument is specified then the record will be updated if it
  1372. * exists rather than adding a new property.
  1373. *
  1374. * @param $basetable
  1375. * The base table for which the property should be inserted. Thus to insert a property
  1376. * for a feature the basetable=feature and property is inserted into featureprop
  1377. * @param $record_id
  1378. * The foriegn key field of the base table. This should be in integer.
  1379. * @param $property
  1380. * The cvterm name describing the type of properties to be inserted
  1381. * @param $cv_name
  1382. * The name of the cv that the above cvterm is part of
  1383. * @param $value
  1384. * The value of the property to be inserted (can be empty)
  1385. * @param $update_if_present
  1386. * A boolean indicating whether an existing record should be updated. If the
  1387. * property already exists and this value is not specified or is zero then
  1388. * a new property will be added with the next largest rank.
  1389. *
  1390. * @return
  1391. * Return True on Insert/Update and False otherwise
  1392. *
  1393. * @ingroup tripal_chado_api
  1394. */
  1395. function tripal_core_insert_property($basetable, $record_id, $property,
  1396. $cv_name, $value, $update_if_present = 0) {
  1397. // first see if the property already exists, if the user want's to update
  1398. // then we can do that, but otherwise we want to increment the rank and
  1399. // insert
  1400. $props = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  1401. if (!is_array($props)) {
  1402. $props = array($props);
  1403. }
  1404. $rank = 0;
  1405. if (count($props)>0) {
  1406. if ($update_if_present) {
  1407. return tripal_core_update_property($basetable, $record_id, $property, $cv_name, $value);
  1408. }
  1409. else {
  1410. // iterate through the properties returned and check to see if the
  1411. // property with this value already exists if not, get the largest rank
  1412. // and insert the same property but with this new value
  1413. foreach ($props as $p) {
  1414. if ($p->rank > $rank) {
  1415. $rank = $p->rank;
  1416. }
  1417. if (strcmp($p->value, $value) == 0) {
  1418. return TRUE;
  1419. }
  1420. }
  1421. // now add 1 to the rank
  1422. $rank++;
  1423. }
  1424. }
  1425. // get the foreign key for this property table
  1426. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1427. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1428. // construct the array of values to be inserted
  1429. $values = array(
  1430. $fkcol => $record_id,
  1431. 'type_id' => array(
  1432. 'cv_id' => array(
  1433. 'name' => $cv_name,
  1434. ),
  1435. 'name' => $property,
  1436. 'is_obsolete' => 0
  1437. ),
  1438. 'value' => $value,
  1439. 'rank' => $rank,
  1440. );
  1441. return tripal_core_chado_insert($basetable . 'prop', $values);
  1442. }
  1443. /**
  1444. * Update a property for a given base table record and property name. This
  1445. * function should be used only if one record of the property will be present.
  1446. * If the property name can have multiple entries (with increasing rank) then
  1447. * use the function named tripal_core_update_property_by_id
  1448. *
  1449. * @param $basetable
  1450. * The base table for which the property should be updated. The property table
  1451. * is constructed using a combination of the base table name and the suffix
  1452. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  1453. * @param $record_id
  1454. * The foreign key of the basetable to update a property for. This should be in integer.
  1455. * For example, if the basetable is 'feature' then the $record_id should be the feature_id
  1456. * @param $property
  1457. * The cvterm name of property to be updated
  1458. * @param $cv_name
  1459. * The name of the cv that the above cvterm is part of
  1460. * @param $value
  1461. * The value of the property to be inserted (can be empty)
  1462. * @param $insert_if_missing
  1463. * A boolean indicating whether a record should be inserted if one doesn't exist to update
  1464. *
  1465. * Note: The property to be updated is select via the unique combination of $record_id and
  1466. * $property and then it is updated with the supplied value
  1467. *
  1468. * @return
  1469. * Return True on Update/Insert and False otherwise
  1470. *
  1471. * @ingroup tripal_chado_api
  1472. */
  1473. function tripal_core_update_property($basetable, $record_id, $property,
  1474. $cv_name, $value, $insert_if_missing = 0) {
  1475. // first see if the property is missing (we can't update a missing property
  1476. $prop = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  1477. if (count($prop)==0) {
  1478. if ($insert_if_missing) {
  1479. return tripal_core_insert_property($basetable, $record_id, $property, $cv_name, $value);
  1480. }
  1481. else {
  1482. return FALSE;
  1483. }
  1484. }
  1485. // get the foreign key for this property table
  1486. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1487. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1488. // construct the array that will match the exact record to update
  1489. $match = array(
  1490. $fkcol => $record_id,
  1491. 'type_id' => array(
  1492. 'cv_id' => array(
  1493. 'name' => $cv_name,
  1494. ),
  1495. 'name' => $property,
  1496. ),
  1497. );
  1498. // construct the array of values to be updated
  1499. $values = array(
  1500. 'value' => $value,
  1501. );
  1502. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  1503. }
  1504. /**
  1505. * Update a property for a given base table record. This function should be
  1506. * used if multiple records of the same property will be present. Also, use this
  1507. * function to change the property name of an existing property.
  1508. *
  1509. * @param $basetable
  1510. * The base table for which the property should be updated. The property table
  1511. * is constructed using a combination of the base table name and the suffix
  1512. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  1513. * @param $record_id
  1514. * The primary key of the base table. This should be in integer.
  1515. * For example, if the basetable is 'feature' then the $record_id should be the featureprop_id
  1516. * @param $property
  1517. * The cvterm name of property to be updated
  1518. * @param $cv_name
  1519. * The name of the cv that the above cvterm is part of
  1520. * @param $value
  1521. * The value of the property to be inserted (can be empty)
  1522. *
  1523. * @return
  1524. * Return True on Update/Insert and False otherwise
  1525. *
  1526. * @ingroup tripal_chado_api
  1527. */
  1528. function tripal_core_update_property_by_id($basetable, $record_id, $property,
  1529. $cv_name, $value) {
  1530. // get the primary key for this property table
  1531. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1532. $pkcol = $table_desc['primary key'][0];
  1533. // construct the array that will match the exact record to update
  1534. $match = array(
  1535. $pkcol => $record_id,
  1536. );
  1537. // construct the array of values to be updated
  1538. $values = array(
  1539. 'type_id' => array(
  1540. 'cv_id' => array(
  1541. 'name' => $cv_name,
  1542. ),
  1543. 'name' => $property,
  1544. ),
  1545. 'value' => $value,
  1546. );
  1547. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  1548. }
  1549. /**
  1550. * Deletes a property for a given base table record using the property name
  1551. *
  1552. * @param $basetable
  1553. * The base table for which the property should be deleted. Thus to deleted a property
  1554. * for a feature the basetable=feature and property is deleted from featureprop
  1555. * @param $record_id
  1556. * The primary key of the basetable to delete a property for. This should be in integer.
  1557. * @param $property
  1558. * The cvterm name describing the type of property to be deleted
  1559. * @param $cv_name
  1560. * The name of the cv that the above cvterm is part of
  1561. *
  1562. * Note: The property to be deleted is select via the unique combination of $record_id and $property
  1563. *
  1564. * @return
  1565. * Return True on Delete and False otherwise
  1566. *
  1567. * @ingroup tripal_chado_api
  1568. */
  1569. function tripal_core_delete_property($basetable, $record_id, $property, $cv_name) {
  1570. // get the foreign key for this property table
  1571. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1572. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1573. // construct the array that will match the exact record to update
  1574. $match = array(
  1575. $fkcol => $record_id,
  1576. 'type_id' => array(
  1577. 'cv_id' => array(
  1578. 'name' => $cv_name,
  1579. ),
  1580. 'name' => $property,
  1581. ),
  1582. );
  1583. return tripal_core_chado_delete($basetable . 'prop', $match);
  1584. }
  1585. /**
  1586. * Deletes a property using the property ID
  1587. *
  1588. * @param $basetable
  1589. * The base table for which the property should be deleted. Thus to deleted a property
  1590. * for a feature the basetable=feature and property is deleted from featureprop
  1591. * @param $record_id
  1592. * The primary key of the basetable to delete a property for. This should be in integer.
  1593. *
  1594. * @return
  1595. * Return True on Delete and False otherwise
  1596. *
  1597. * @ingroup tripal_chado_api
  1598. */
  1599. function tripal_core_delete_property_by_id($basetable, $record_id) {
  1600. // get the foreign key for this property table
  1601. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1602. $pkcol = $table_desc['primary key'][0];
  1603. // construct the array that will match the exact record to update
  1604. $match = array(
  1605. $pkcol => $record_id,
  1606. );
  1607. return tripal_core_chado_delete($basetable . 'prop', $match);
  1608. }
  1609. /**
  1610. * This function is typically used in the '.install' file for a Tripal module
  1611. * Each module should call this function during installation to create
  1612. * the module data directory which is sites/default/files/tripal/[module_name]
  1613. * for default Drupal settings. This directory can then be used by the module
  1614. * for storing files.
  1615. *
  1616. * @param $module_name
  1617. * the name of the module being installed.
  1618. *
  1619. * @returns
  1620. * nothing
  1621. *
  1622. * @ingroup tripal_files_api
  1623. */
  1624. function tripal_create_moddir($module_name) {
  1625. // make the data directory for this module
  1626. $data_dir = file_directory_path() . "/tripal/$module_name";
  1627. if (!file_check_directory($data_dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
  1628. $message = "Cannot create directory $data_dir. This module may not ".
  1629. "behave correctly without this directory. Please create ".
  1630. "the directory manually or fix the problem and reinstall.";
  1631. drupal_set_message(check_plain(t($message)), 'error');
  1632. watchdog('tripal_core', $message, array(), WATCHDOG_ERROR);
  1633. }
  1634. }
  1635. /**
  1636. * Each Tripal module has a unique data directory which was creatd using the
  1637. * tripal_create_moddir function during installation. This function
  1638. * retrieves the directory path.
  1639. *
  1640. * @param $module_name
  1641. * The name of the module
  1642. *
  1643. * @returns
  1644. * The path within the Drupal installation where the data directory resides
  1645. * @ingroup tripal_files_api
  1646. */
  1647. function tripal_get_moddir($module_name) {
  1648. $data_dir = file_directory_path() . "/tripal/$module_name";
  1649. return $data_dir;
  1650. }
  1651. /**
  1652. * Set the Tripal Database
  1653. *
  1654. * The tripal_db_set_active function is used to prevent namespace collisions
  1655. * when chado and drupal are installed in the same database but in different
  1656. * schemas. It is also used for backwards compatibility with older versions
  1657. * of tripal or in cases where chado is located outside of the Drupal database.
  1658. *
  1659. * @ingroup tripal_chado_api
  1660. */
  1661. function tripal_db_set_active($dbname) {
  1662. global $db_url, $db_type;
  1663. $chado_exists = 0;
  1664. // only postgres can support search paths. So if this is MysQL then
  1665. // just run the normal tripal_db_set_active function.
  1666. if (strcmp($db_type, 'pgsql')==0) {
  1667. // if the 'chado' database is in the $db_url variable then chado is
  1668. // not in the same Drupal database
  1669. if (is_array($db_url)) {
  1670. if (isset($db_url[$dbname])) {
  1671. return db_set_active($dbname);
  1672. }
  1673. }
  1674. // check to make sure the chado schema exists
  1675. $chado_exists = tripal_core_chado_schema_exists();
  1676. // here we make the assumption that the default database schema is
  1677. // 'public'. This will most likely always be the case but if not,
  1678. // then this code will break
  1679. if ($chado_exists && strcmp($dbname, 'chado')==0) {
  1680. db_query("set search_path to %s", 'chado,public');
  1681. return 'public,chado';
  1682. }
  1683. elseif ($chado_exists) {
  1684. db_query("set search_path to %s", 'public,chado');
  1685. return 'chado,public';
  1686. }
  1687. else {
  1688. return db_set_active($dbname);
  1689. }
  1690. }
  1691. else {
  1692. return db_set_active($dbname);
  1693. }
  1694. }
  1695. /**
  1696. * Purpose: Get max rank for a given set of criteria
  1697. * This function was developed with the many property tables in chado in mind
  1698. *
  1699. * @param $tablename
  1700. * The name of the chado table you want to select the max rank from this table must contain a
  1701. * rank column of type integer
  1702. * @param $where_options
  1703. * where options should include the id and type for that table to correctly
  1704. * group a set of records together where the only difference are the value and rank
  1705. * @code
  1706. * array(
  1707. * <column_name> => array(
  1708. * 'type' => <type of column: INT/STRING>,
  1709. * 'value' => <the value you want to filter on>,
  1710. * 'exact' => <if TRUE use =; if FALSE use ~>,
  1711. * )
  1712. * )
  1713. * @endcode
  1714. * @return the maximum rank
  1715. *
  1716. * @ingroup tripal_chado_api
  1717. */
  1718. function tripal_get_max_chado_rank($tablename, $where_options) {
  1719. $where= array();
  1720. //generate the where clause from supplied options
  1721. // the key is the column name
  1722. foreach ($where_options as $key => $val_array) {
  1723. if (preg_match('/INT/', $val_array['type'])) {
  1724. $where[] = $key . "=" . $val_array['value'];
  1725. }
  1726. else {
  1727. if ($val_array['exact']) {
  1728. $operator='=';
  1729. }
  1730. else {
  1731. $operator='~';
  1732. }
  1733. $where[] = $key . $operator . "'" . $val_array['value'] . "'";
  1734. }
  1735. }
  1736. $previous_db = tripal_db_set_active('chado');
  1737. $result = db_fetch_object(db_query(
  1738. "SELECT max(rank) as max_rank, count(rank) as count FROM %s WHERE %s",
  1739. $tablename,
  1740. implode(' AND ', $where)
  1741. ));
  1742. tripal_db_set_active($previous_db);
  1743. //drupal_set_message("Max Rank Query=SELECT max(rank) as max_rank, count(rank) as count FROM ".$tablename." WHERE ".implode(' AND ',$where));
  1744. if ($result->count > 0) {
  1745. return $result->max_rank;
  1746. }
  1747. else {
  1748. return -1;
  1749. }
  1750. }
  1751. /**
  1752. * Add a new table to the Chado schema. This function is simply a wrapper for
  1753. * the db_create_table() function of Drupal, but ensures the table is created
  1754. * inside the Chado schema rather than the Drupal schema. If the table already
  1755. * exists then it will be dropped and recreated using the schema provided.
  1756. * Howver, it will only drop a table if it exsits in the tripal_custom_tables
  1757. * table. This way the function cannot be used to accidentally alter existing
  1758. * non custom tables.
  1759. *
  1760. * @param $ret
  1761. * Array to which query results will be added.
  1762. * @param $table
  1763. * The name of the table to create.
  1764. * @param $schema
  1765. * A Drupal-style Schema API definition of the table
  1766. *
  1767. * @return
  1768. * A database query result resource for the new table, or FALSE if table was not constructed.
  1769. *
  1770. * @ingroup tripal_core_api
  1771. */
  1772. function tripal_create_chado_table(&$ret, $table, $schema) {
  1773. $ret = array();
  1774. // If the table exits in Chado but not in the tripal_custom_tables field
  1775. // then call an error. if the table exits in the tripal_custom_tables but
  1776. // not in Chado then create the table and replace the entry.
  1777. $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_name = '%s'";
  1778. $centry = db_fetch_object(db_query($sql, $table));
  1779. $previous_db = tripal_db_set_active('chado'); // use chado database
  1780. $exists = db_table_exists($table);
  1781. tripal_db_set_active($previous_db); // now use drupal database
  1782. if (!$exists) {
  1783. $previous_db = tripal_db_set_active('chado'); // use chado database
  1784. db_create_table($ret, $table, $schema);
  1785. tripal_db_set_active($previous_db); // now use drupal database
  1786. if (count($ret)==0) {
  1787. watchdog('tripal_core', "Error adding custom table '!table_name'.",
  1788. array('!table_name' => $table), WATCHDOG_ERROR);
  1789. return FALSE;
  1790. }
  1791. }
  1792. if ($exists and !$centry) {
  1793. watchdog('tripal_core', "Could not add custom table '!table_name'. It ".
  1794. "already exists but is not known to Tripal as being a custom table.",
  1795. array('!table_name' => $table), WATCHDOG_WARNING);
  1796. return FALSE;
  1797. }
  1798. if ($exists and $centry) {
  1799. // drop the table we'll recreate it with the new schema
  1800. $previous_db = tripal_db_set_active('chado'); // use chado database
  1801. db_drop_table($ret, $table);
  1802. db_create_table($ret, $table, $schema);
  1803. tripal_db_set_active($previous_db); // now use drupal database
  1804. }
  1805. // if the table creation was succesful then add an entry
  1806. // in the tripal_custom_table
  1807. $record = new stdClass();
  1808. $record->table_name = $table;
  1809. $record->schema = serialize($schema);
  1810. // if an entry already exists then remove it
  1811. if ($centry) {
  1812. $sql = "DELETE FROM {tripal_custom_tables} WHERE table_name = '%s'";
  1813. db_query($sql, $table);
  1814. }
  1815. $success = drupal_write_record('tripal_custom_tables', $record);
  1816. if (!$success) {
  1817. watchdog('tripal_core', "Error adding custom table.",
  1818. array('!table_name' => $table), WATCHDOG_ERROR);
  1819. return FALSE;
  1820. }
  1821. return $ret;
  1822. }
  1823. /**
  1824. * Retrieves the schema in an array for the specified custom table.
  1825. *
  1826. * @param $table
  1827. * The name of the table to create.
  1828. *
  1829. * @return
  1830. * A Drupal-style Schema API array definition of the table. Returns
  1831. * FALSE on failure.
  1832. *
  1833. * @ingroup tripal_core_api
  1834. */
  1835. function tripal_get_chado_custom_schema($table) {
  1836. $sql = "SELECT schema FROM {tripal_custom_tables} WHERE table_name = '%s'";
  1837. $custom = db_fetch_object(db_query($sql, $table));
  1838. if (!$custom) {
  1839. return FALSE;
  1840. }
  1841. else {
  1842. return unserialize($custom->schema);
  1843. }
  1844. }
  1845. /**
  1846. * Check that the Chado schema exists
  1847. *
  1848. * @return
  1849. * TRUE/FALSE depending upon whether it exists
  1850. */
  1851. function tripal_core_chado_schema_exists() {
  1852. // This is postgresql-specific code to check the existence of the chado schema
  1853. $sql = "SELECT nspname FROM pg_catalog.pg_namespace WHERE nspname = 'chado'";
  1854. if (db_fetch_object(db_query($sql))) {
  1855. return TRUE;
  1856. }
  1857. else {
  1858. return FALSE;
  1859. }
  1860. }