tripal_core.api.inc 132 KB

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