tripal_core.api.inc 118 KB

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