tripal_core.api.inc 106 KB

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