tripal_core_chado.api.inc 105 KB

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