tripal_core.api.inc 79 KB

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