tripal_core.api.inc 79 KB

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