tripal_core.api.inc 83 KB

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