tripal_core.api.inc 120 KB

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