tripal_core.api.inc 106 KB

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