tripal_core.api.inc 78 KB

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