tripal_core.api.inc 88 KB

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