tripal_core.api.inc 99 KB

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