tripal_core.api.inc 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166
  1. <?php
  2. require_once "tripal_core.schema.api.inc";
  3. /**
  4. * @file
  5. * The Tripal Core API
  6. *
  7. * This file provides the API needed for all other Tripal and Tripal dependent
  8. * modules.
  9. *
  10. * @defgroup tripal_api Tripal API
  11. * @{
  12. * Provides an application programming interface (API) for Tripal
  13. *
  14. * The Tripal API currently provides generic insert/update/select functions for all chado content as
  15. * well as some module specific functions that insert/update/delete/select specific chado content.
  16. *
  17. * This API is currently in its infancy and some necessary functions might be missing. If you find
  18. * a missing function that you think should be included go to the sourceforge feature request
  19. * page and request it's inclusion in the API. Such feature requests with a working function
  20. * definition will be given priority.
  21. * @}
  22. *
  23. * @defgroup tripal_chado_api Core Module Chado API
  24. * @{
  25. * Provides an application programming interface (API) to manage data withing the Chado database.
  26. * This includes functions for selecting, inserting, updating and deleting records
  27. * in Chado tables. The functions will ensure proper integrity contraints are met
  28. * for inserts and updates.
  29. *
  30. * Also, a set of functions is provided for creating template variables. First,
  31. * is the tripal_core_generate_chado_vars which is used to select one ore more
  32. * records from a table and return an array with foreign key relationships fully
  33. * populated. For example, if selecting a feature, the organism_id and type_id
  34. * would be present in the returned array as a nested array with their respective
  35. * foreign keys also nested. The only fields that are not included are text
  36. * fields (which may be very large) or many-to-many foreign key relationships.
  37. * However, these fields and relationships can be expanded using the
  38. * tripal_core_expand_chado_vars.
  39. *
  40. * When a row from a chado table is selected using these two functions, it provides
  41. * a way for users who want to cutomize Drupal template files to access all data
  42. * associate with a specific record.
  43. *
  44. * Finally, the property tables in Chado generally follow the same format. Therefore
  45. * there is a set of functions for inserting, updating and deleting properties for
  46. * any table. This provides quick lookup of properties (provided the CV term is
  47. * known).
  48. *
  49. * @}
  50. * @ingroup tripal_api
  51. *
  52. * @defgroup tripal_files_api Core Module Files API
  53. * @{
  54. * Provides an application programming interface (API) for managing files within
  55. * the Tripal data directory structure.
  56. *
  57. * @}
  58. * @ingroup tripal_api
  59. /**
  60. * Provides a generic routine for inserting into any Chado table
  61. *
  62. * Use this function to insert a record into any Chado table. The first
  63. * argument specifies the table for inserting and the second is an array
  64. * of values to be inserted. The array is mutli-dimensional such that
  65. * foreign key lookup values can be specified.
  66. *
  67. * @param $table
  68. * The name of the chado table for inserting
  69. * @param $values
  70. * An associative array containing the values for inserting.
  71. * @param $options
  72. * An array of options such as:
  73. * -prepare: TRUE or FALSE. Whether or not to prepare the current statement.
  74. * statement_name must also be supplied.
  75. * -statement_name: the name of the prepared statement to use. If prepare is TRUE,
  76. * this indicates the name of the prepared statement to created; otherwise,
  77. * it indicates the name of the already prepared statement to use.
  78. * -skip_validation: TRUE or FALSE. If TRUE will skip all the validation steps and
  79. * just try to insert as is. This is much faster but results in unhandled
  80. * non user-friendly errors if the insert fails.
  81. *
  82. * @return
  83. * On success this function returns TRUE. On failure, it returns FALSE.
  84. *
  85. * Example usage:
  86. * @code
  87. * $values = array(
  88. * 'organism_id' => array(
  89. * 'genus' => 'Citrus',
  90. * 'species' => 'sinensis',
  91. * ),
  92. * 'name' => 'orange1.1g000034m.g',
  93. * 'uniquename' => 'orange1.1g000034m.g',
  94. * 'type_id' => array (
  95. * 'cv_id' => array (
  96. * 'name' => 'sequence',
  97. * ),
  98. * 'name' => 'gene',
  99. * 'is_obsolete' => 0
  100. * ),
  101. * );
  102. * $result = tripal_core_chado_insert('feature',$values);
  103. * @endcode
  104. * The above code inserts a record into the feature table. The $values array is
  105. * nested such that the organism is selected by way of the organism_id foreign
  106. * key constraint by specifying the genus and species. The cvterm is also
  107. * specified using its foreign key and the cv_id for the cvterm is nested as
  108. * well.
  109. *
  110. * @ingroup tripal_chado_api
  111. */
  112. function tripal_core_chado_insert($table, $values, $options = array()) {
  113. $insert_values = array();
  114. $chado_db = tripal_db_persistent_chado();
  115. // Determine plan of action
  116. if ($options['statement_name']) {
  117. $prepared = TRUE;
  118. $connection = tripal_db_persistent_chado();
  119. if ($options['prepare']) {
  120. $build_sql = TRUE;
  121. }
  122. else {
  123. $build_sql = FALSE;
  124. }
  125. }
  126. else {
  127. $build_sql = TRUE;
  128. }
  129. if (array_key_exists('skip_validation', $options)) {
  130. $validate = !$options['skip_validation'];
  131. }
  132. else {
  133. $validate = TRUE;
  134. }
  135. // get the table description
  136. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  137. if (empty($table_desc)) {
  138. watchdog('tripal_core', 'tripal_core_chado_insert: There is no table description for !table_name', array('!table_name' => $table), WATCHDOG_WARNING);
  139. }
  140. // iterate through the values array and create a new 'insert_values' array
  141. // that has all the values needed for insert with all foreign relationsihps
  142. // resolved.
  143. foreach ($values as $field => $value) {
  144. if (is_array($value)) {
  145. // select the value from the foreign key relationship for this value
  146. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
  147. if (sizeof($results) > 1) {
  148. 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);
  149. }
  150. elseif (sizeof($results) < 1) {
  151. //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);
  152. }
  153. else {
  154. $insert_values[$field] = $results[0];
  155. }
  156. }
  157. else {
  158. $insert_values[$field] = $value;
  159. }
  160. }
  161. if ($validate) {
  162. // check for violation of any unique constraints
  163. $ukeys = $table_desc['unique keys'];
  164. $ukselect_cols = array();
  165. $ukselect_vals = array();
  166. if ($ukeys) {
  167. foreach ($ukeys as $name => $fields) {
  168. foreach ($fields as $index => $field) {
  169. // build the arrays for performing a select that will check the contraint
  170. array_push($ukselect_cols, $field);
  171. $ukselect_vals[$field] = $insert_values[$field];
  172. }
  173. // now check the constraint
  174. if (tripal_core_chado_select($table, $ukselect_cols, $ukselect_vals)) {
  175. watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert duplicate record into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  176. return FALSE;
  177. }
  178. }
  179. }
  180. // if trying to insert a field that is the primary key, make sure it also is unique
  181. $pkey = $table_desc['primary key'][0];
  182. if ($insert_values[$pkey]) {
  183. if (tripal_core_chado_select($table, array($pkey), array($pkey => $insert_values[$pkey]))) {
  184. watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert duplicate primary key into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  185. return FALSE;
  186. }
  187. }
  188. // make sure required fields have a value
  189. if (!is_array($table_desc['fields'])) {
  190. $table_desc['fields'] = array();
  191. watchdog('tripal_core', "tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
  192. }
  193. foreach ($table_desc['fields'] as $field => $def) {
  194. // a field is considered missing if it cannot be NULL and there is no default
  195. // value for it or it is of type 'serial'
  196. if ($def['not NULL'] == 1 and !array_key_exists($field, $insert_values) and !isset($def['default']) and strcmp($def['type'], serial) != 0) {
  197. watchdog('tripal_core', "tripal_core_chado_insert: Field $table.$field cannot be NULL: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  198. return FALSE;
  199. }
  200. }
  201. } //end of validation
  202. // Now build the insert SQL statement
  203. $ifields = array(); //contains the names of the fields
  204. $ivalues = array(); //contains the values of the fields
  205. $itypes = array(); // contains %d/%s placeholders for the sql query
  206. $iplaceholders = array(); // contains $1/$2 placeholders for the prepare query
  207. $idatatypes = array(); //contains the data type of the fields (int, text, etc.)
  208. $i = 1;
  209. foreach ($insert_values as $field => $value) {
  210. $ifields[] = $field;
  211. $ivalues[] = $value;
  212. $iplaceholders[] = '$' . $i;
  213. $i++;
  214. if (strcmp($value, '__NULL__')==0) {
  215. $itypes[] = "NULL";
  216. $idatatypes[] = "NULL";
  217. }
  218. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'serial')==0 OR
  219. strcasecmp($table_desc['fields'][$field]['type'], 'int')==0 OR
  220. strcasecmp($table_desc['fields'][$field]['type'], 'integer')==0) {
  221. $itypes[] = "%d";
  222. $idatatypes[] = 'int';
  223. }
  224. else {
  225. $itypes[] = "'%s'";
  226. $idatatypes[] = 'text';
  227. }
  228. }
  229. if ($build_sql) {
  230. // prepare the statement
  231. if ($prepared) {
  232. $prepare_sql = "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS INSERT INTO {$table} (" . implode(", ", $ifields) . ") VALUES (" . implode(", ", $iplaceholders) . ")";
  233. $status = chado_query($prepare_sql);
  234. if (!$status) {
  235. watchdog('tripal_core', "tripal_core_chado_insert: not able to prepare '%name' statement for: %sql", array('%name' => $options['statement_name'], '%sql' => $sql), 'WATCHDOG ERROR');
  236. return FALSE;
  237. }
  238. }
  239. else {
  240. $sql = "INSERT INTO {$table} (" . implode(", ", $ifields) . ") VALUES (" . implode(", ", $itypes) . ")";
  241. }
  242. }
  243. // finally perform the insert.
  244. if ($prepared) {
  245. $sql = "EXECUTE " . $options['statement_name'] . "(" . implode(", ", $itypes) . ")";
  246. $result = chado_query($sql, $ivalues);
  247. if ($result) {
  248. // add primary keys to values before return
  249. $primary_key = array();
  250. if (!is_array($table_desc['primary key'])) {
  251. $table_desc['primary key'] = array();
  252. watchdog('tripal_core', "tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
  253. }
  254. foreach ($table_desc['primary key'] as $field) {
  255. $value = db_last_insert_id($table, $field);
  256. $values[$field] = $value;
  257. }
  258. return $values;
  259. }
  260. else {
  261. watchdog('tripal_core', "tripal_core_chado_insert: not able to execute prepared statement '%name' with values: %values", array('%name' => $options['statement_name'], '%values' => print_r($values, TRUE)), 'WATCHDOG ERROR');
  262. return FALSE;
  263. }
  264. }
  265. else {
  266. $previous_db = tripal_db_set_active('chado'); // use chado database
  267. $result = db_query($sql, $ivalues);
  268. tripal_db_set_active($previous_db); // now use drupal database
  269. if ($result) {
  270. // add primary keys to values before return
  271. $primary_key = array();
  272. if (!is_array($table_desc['primary key'])) {
  273. $table_desc['primary key'] = array();
  274. watchdog('tripal_core', "tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
  275. }
  276. foreach ($table_desc['primary key'] as $field) {
  277. $value = db_last_insert_id($table, $field);
  278. $values[$field] = $value;
  279. }
  280. return $values;
  281. }
  282. else {
  283. watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert record into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  284. return FALSE;
  285. }
  286. }
  287. return FALSE;
  288. }
  289. /**
  290. * Provides a generic function for deleting a record(s) from any chado table
  291. *
  292. * Use this function to delete a record(s) in any Chado table. The first
  293. * argument specifies the table to delete from and the second is an array
  294. * of values to match for locating the record(s) to be deleted. The arrays
  295. * are mutli-dimensional such that foreign key lookup values can be specified.
  296. *
  297. * @param $table
  298. * The name of the chado table for inserting
  299. * @param $match
  300. * An associative array containing the values for locating a record to update.
  301. *
  302. * @return
  303. * On success this function returns TRUE. On failure, it returns FALSE.
  304. *
  305. * Example usage:
  306. * @code
  307. $umatch = array(
  308. 'organism_id' => array(
  309. 'genus' => 'Citrus',
  310. 'species' => 'sinensis',
  311. ),
  312. 'uniquename' => 'orange1.1g000034m.g7',
  313. 'type_id' => array (
  314. 'cv_id' => array (
  315. 'name' => 'sequence',
  316. ),
  317. 'name' => 'gene',
  318. 'is_obsolete' => 0
  319. ),
  320. );
  321. $uvalues = array(
  322. 'name' => 'orange1.1g000034m.g',
  323. 'type_id' => array (
  324. 'cv_id' => array (
  325. 'name' => 'sequence',
  326. ),
  327. 'name' => 'mRNA',
  328. 'is_obsolete' => 0
  329. ),
  330. );
  331. * $result = tripal_core_chado_update('feature',$umatch,$uvalues);
  332. * @endcode
  333. * The above code species that a feature with a given uniquename, organism_id,
  334. * and type_id (the unique constraint for the feature table) will be deleted.
  335. * The organism_id is specified as a nested array that uses the organism_id
  336. * foreign key constraint to lookup the specified values to find the exact
  337. * organism_id. The same nested struture is also used for specifying the
  338. * values to update. The function will find all records that match the
  339. * columns specified and delete them.
  340. *
  341. * @ingroup tripal_chado_api
  342. */
  343. function tripal_core_chado_delete($table, $match) {
  344. $delete_matches = array(); // contains the values for the where clause
  345. // get the table description
  346. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  347. // get the values needed for matching in the SQL statement
  348. foreach ($match as $field => $value) {
  349. if (is_array($value)) {
  350. // if the user has specified an array of values to delete rather than
  351. // FK relationships the keep those in our match
  352. if (array_values($value) === $value) {
  353. $delete_matches[$field] = $value;
  354. }
  355. else {
  356. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
  357. if (sizeof($results) > 1) {
  358. 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);
  359. }
  360. elseif (sizeof($results) < 1) {
  361. //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);
  362. }
  363. else {
  364. $delete_matches[$field] = $results[0];
  365. }
  366. }
  367. }
  368. else {
  369. $delete_matches[$field] = $value;
  370. }
  371. }
  372. // now build the SQL statement
  373. $sql = "DELETE FROM {$table} WHERE ";
  374. $dargs = array();
  375. foreach ($delete_matches as $field => $value) {
  376. if (count($value) > 1) {
  377. $sql .= "$field IN (" . db_placeholders($value, 'varchar') . ") AND ";
  378. foreach ($value as $v) {
  379. $dargs[] = $v;
  380. }
  381. }
  382. else {
  383. if (strcmp($value, '__NULL__') == 0) {
  384. $sql .= " $field = NULL AND ";
  385. }
  386. elseif (strcmp($fields[$field]['type'], 'serial') == 0 or
  387. strcmp($fields[$field]['type'], 'int') == 0) {
  388. $sql .= " $field = %d AND ";
  389. }
  390. else {
  391. $sql .= " $field = '%s' AND ";
  392. }
  393. array_push($dargs, $value);
  394. }
  395. }
  396. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND'
  397. // finally perform the delete. If successful, return the updated record
  398. $previous_db = tripal_db_set_active('chado'); // use chado database
  399. $result = db_query($sql, $dargs);
  400. tripal_db_set_active($previous_db); // now use drupal database
  401. if ($result) {
  402. return TRUE;
  403. }
  404. else {
  405. watchdog('tripal_core', "Cannot delete record in $table table. Match:" . print_r($match, 1) . ". Values: ". print_r($values, 1), array(), 'WATCHDOG_ERROR');
  406. return FALSE;
  407. }
  408. return FALSE;
  409. }
  410. /**
  411. * Provides a generic routine for updating into any Chado table
  412. *
  413. * Use this function to update a record in any Chado table. The first
  414. * argument specifies the table for inserting, the second is an array
  415. * of values to matched for locating the record for updating, and the third
  416. * argument give the values to update. The arrays are mutli-dimensional such
  417. * that foreign key lookup values can be specified.
  418. *
  419. * @param $table
  420. * The name of the chado table for inserting
  421. * @param $match
  422. * An associative array containing the values for locating a record to update.
  423. * @param $values
  424. * An associative array containing the values for updating.
  425. *
  426. * @return
  427. * On success this function returns TRUE. On failure, it returns FALSE.
  428. *
  429. * Example usage:
  430. * @code
  431. $umatch = array(
  432. 'organism_id' => array(
  433. 'genus' => 'Citrus',
  434. 'species' => 'sinensis',
  435. ),
  436. 'uniquename' => 'orange1.1g000034m.g7',
  437. 'type_id' => array (
  438. 'cv_id' => array (
  439. 'name' => 'sequence',
  440. ),
  441. 'name' => 'gene',
  442. 'is_obsolete' => 0
  443. ),
  444. );
  445. $uvalues = array(
  446. 'name' => 'orange1.1g000034m.g',
  447. 'type_id' => array (
  448. 'cv_id' => array (
  449. 'name' => 'sequence',
  450. ),
  451. 'name' => 'mRNA',
  452. 'is_obsolete' => 0
  453. ),
  454. );
  455. * $result = tripal_core_chado_update('feature',$umatch,$uvalues);
  456. * @endcode
  457. * The above code species that a feature with a given uniquename, organism_id,
  458. * and type_id (the unique constraint for the feature table) will be updated.
  459. * The organism_id is specified as a nested array that uses the organism_id
  460. * foreign key constraint to lookup the specified values to find the exact
  461. * organism_id. The same nested struture is also used for specifying the
  462. * values to update. The function will find the record that matches the
  463. * columns specified and update the record with the avlues in the $uvalues array.
  464. *
  465. * @ingroup tripal_chado_api
  466. */
  467. function tripal_core_chado_update($table, $match, $values) {
  468. $update_values = array(); // contains the values to be updated
  469. $update_matches = array(); // contains the values for the where clause
  470. // get the table description
  471. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  472. // get the values needed for matching in the SQL statement
  473. foreach ($match as $field => $value) {
  474. if (is_array($value)) {
  475. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
  476. if (sizeof($results) > 1) {
  477. 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);
  478. }
  479. elseif (sizeof($results) < 1) {
  480. //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);
  481. }
  482. else {
  483. $update_matches[$field] = $results[0];
  484. }
  485. }
  486. else {
  487. $update_matches[$field] = $value;
  488. }
  489. }
  490. // get the values used for updating
  491. foreach ($values as $field => $value) {
  492. if (is_array($value)) {
  493. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
  494. if (sizeof($results) > 1) {
  495. 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);
  496. }
  497. elseif (sizeof($results) < 1) {
  498. //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);
  499. }
  500. else {
  501. $update_values[$field] = $results[0];
  502. }
  503. }
  504. else {
  505. $update_values[$field] = $value;
  506. }
  507. }
  508. // now build the SQL statement
  509. $sql = "UPDATE {$table} SET ";
  510. $fields = $table_desc['fields'];
  511. $uargs = array();
  512. foreach ($update_values as $field => $value) {
  513. if (strcmp($value, '__NULL__') == 0) {
  514. $sql .= " $field = NULL, ";
  515. }
  516. elseif (strcmp($fields[$field]['type'], 'serial')==0 or
  517. strcmp($fields[$field]['type'], 'int')==0) {
  518. $sql .= " $field = %d, ";
  519. }
  520. else {
  521. $sql .= " $field = '%s', ";
  522. }
  523. array_push($uargs, $value);
  524. }
  525. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing comma & space
  526. $sql .= " WHERE ";
  527. foreach ($update_matches as $field => $value) {
  528. if (strcmp($value, '__NULL__')==0) {
  529. $sql .= " $field = NULL AND ";
  530. }
  531. elseif (strcmp($fields[$field]['type'], 'serial')==0 or
  532. strcmp($fields[$field]['type'], 'int')==0) {
  533. $sql .= " $field = %d AND ";
  534. }
  535. else {
  536. $sql .= " $field = '%s' AND ";
  537. }
  538. array_push($uargs, $value);
  539. }
  540. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND'
  541. // finally perform the update. If successful, return the updated record
  542. $previous_db = tripal_db_set_active('chado'); // use chado database
  543. $result = db_query($sql, $uargs);
  544. tripal_db_set_active($previous_db); // now use drupal database
  545. if ($result) {
  546. return TRUE;
  547. }
  548. else {
  549. watchdog('tripal_core', "Cannot update record in $table table. Match:" . print_r($match, 1) . ". Values: ". print_r($values, 1), array(), 'WATCHDOG_ERROR');
  550. return FALSE;
  551. }
  552. return FALSE;
  553. }
  554. /**
  555. * Provides a generic routine for selecting data from a Chado table
  556. *
  557. * Use this function to perform a simple select from any Chado table.
  558. *
  559. * @param $table
  560. * The name of the chado table for inserting
  561. * @param $columns
  562. * An array of column names
  563. * @param $values
  564. * An associative array containing the values for filtering the results. In the
  565. * case where multiple values for the same time are to be selected an additional
  566. * entry for the field should appear for each value
  567. * @param $options
  568. * An associative array of additional options where the key is the option
  569. * and the value is the value of that option.
  570. *
  571. * Additional Options Include:
  572. * - has_record
  573. * Set this argument to 'TRUE' to have this function return a numeric
  574. * value for the number of recrods rather than the array of records. this
  575. * can be useful in 'if' statements to check the presence of particula records.
  576. * - return_sql
  577. * Set this to 'TRUE' to have this function return an array where the first
  578. * element is the sql that would have been run and the second is an array of
  579. * arguments.
  580. * - case_insensitive_columns
  581. * An array of columns to do a case insensitive search on.
  582. * - regex_columns
  583. * An array of columns where the value passed in should be treated as a regular expression
  584. * - order_by
  585. * An associative array containing the column names of the table as keys
  586. * and the type of sort (i.e. ASC, DESC) as the values. The results in the
  587. * query will be sorted by the key values in the direction listed by the value
  588. *
  589. * @return
  590. * A database query result resource, FALSE if the query was not executed
  591. * correctly, or the number of records in the dataset if $has_record is set.
  592. *
  593. * Example usage:
  594. * @code
  595. * $columns = array('feature_id', 'name');
  596. * $values = array(
  597. * 'organism_id' => array(
  598. * 'genus' => 'Citrus',
  599. * 'species' => array('sinensis', 'clementina'),
  600. * ),
  601. * 'uniquename' => 'orange1.1g000034m.g',
  602. * 'type_id' => array (
  603. * 'cv_id' => array (
  604. * 'name' => 'sequence',
  605. * ),
  606. * 'name' => 'gene',
  607. * 'is_obsolete' => 0
  608. * ),
  609. * );
  610. * $result = tripal_core_chado_select('feature',$columns,$values);
  611. * @endcode
  612. * The above code selects a record from the feature table using the three fields
  613. * that uniquely identify a feature. The $columns array simply lists the columns
  614. * to select. The $values array is nested such that the organism is identified by
  615. * way of the organism_id foreign key constraint by specifying the genus and
  616. * species. The cvterm is also specified using its foreign key and the cv_id
  617. * for the cvterm is nested as well. In the example above, two different species
  618. * are allowed to match
  619. *
  620. * @ingroup tripal_chado_api
  621. */
  622. function tripal_core_chado_select($table, $columns, $values, $options = NULL) {
  623. if (!is_array($options)) {
  624. $options = array();
  625. }
  626. if (!$options['case_insensitive_columns']) {
  627. $options['case_insensitive_columns'] = array();
  628. }
  629. if (!$options['regex_columns']) {
  630. $options['regex_columns'] = array();
  631. }
  632. if (!$options['order_by']) {
  633. $options['order_by'] = array();
  634. }
  635. if (!is_array($columns)) {
  636. watchdog('tripal_core', 'the $columns argument for tripal_core_chado_select must be an array.');
  637. return FALSE;
  638. }
  639. if (!is_array($values)) {
  640. watchdog('tripal_core', 'the $values argument for tripal_core_chado_select must be an array.');
  641. return FALSE;
  642. }
  643. // get the table description
  644. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  645. $select = '';
  646. $from = '';
  647. $where = '';
  648. $args = array();
  649. foreach ($values as $field => $value) {
  650. $select[] = $field;
  651. if (is_array($value)) {
  652. // if the user has specified multiple values for matching then this we
  653. // want to catch that and save them in our $where array, otherwise
  654. // we'll descend for a foreign key relationship
  655. if (array_values($value) === $value) {
  656. $where[$field] = $value;
  657. }
  658. else {
  659. // select the value from the foreign key relationship for this value
  660. $foreign_options = array(
  661. 'regex_columns' => $options['regex_columns'],
  662. 'case_insensitive_columns' => $options['case_insensitive_columns']
  663. );
  664. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
  665. if (count($results) ==0) {
  666. // foreign key records are required
  667. // thus if none matched then return FALSE and alert the admin through watchdog
  668. //watchdog('tripal_core',
  669. // 'tripal_core_chado_select: no record in the table referenced by the foreign key (!field) exists. tripal_core_chado_select table=!table, columns=!columns, values=!values',
  670. // array('!table' => $table,
  671. // '!columns' => '<pre>' . print_r($columns, TRUE) . '</pre>',
  672. // '!values' => '<pre>' . print_r($values, TRUE) . '</pre>',
  673. // '!field' => $field,
  674. // ),
  675. // WATCHDOG_WARNING);
  676. return FALSE;
  677. }
  678. else {
  679. $where[$field] = $results;
  680. }
  681. }
  682. }
  683. else {
  684. //need to catch a 0 and make int if integer field
  685. if ($table_desc['fields'][$field]['type'] == 'int') {
  686. $where[$field][] = (int) $value;
  687. }
  688. else {
  689. $where[$field][] = $value;
  690. }
  691. }
  692. }
  693. // now build the SQL select statement
  694. if (empty($where)) {
  695. // sometimes want to select everything
  696. $sql = "SELECT " . implode(', ', $columns) . " ";
  697. $sql .= "FROM {$table} ";
  698. }
  699. else {
  700. $sql = "SELECT " . implode(', ', $columns) . " ";
  701. $sql .= "FROM {$table} ";
  702. $sql .= "WHERE ";
  703. foreach ($where as $field => $value) {
  704. if (count($value) > 1) {
  705. $sql .= "$field IN (" . db_placeholders($value, 'varchar') . ") AND ";
  706. foreach ($value as $v) {
  707. $args[] = $v;
  708. }
  709. }
  710. else {
  711. $operator = '=';
  712. if (in_array($field, $options['regex_columns'])) {
  713. $operator = '~*';
  714. }
  715. if (in_array($field, $options['case_insensitive_columns'])) {
  716. $sql .= "lower($field) $operator lower('%s') AND ";
  717. $args[] = $value[0];
  718. }
  719. else {
  720. $sql .= "$field $operator '%s' AND ";
  721. $args[] = $value[0];
  722. }
  723. }
  724. }
  725. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND '
  726. }
  727. // finally add any ordering of the results to the SQL statement
  728. if (count($options['order_by']) > 0) {
  729. $sql .= " ORDER BY ";
  730. foreach ($options['order_by'] as $field => $dir) {
  731. $sql .= "$field $dir, ";
  732. }
  733. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing ', '
  734. }
  735. // if the caller has requested the SQL rather than the results...
  736. // which happens in the case of wanting to use the Drupal pager, then do so
  737. if ($options['return_sql']) {
  738. return array('sql' => $sql, 'args' => $args);
  739. }
  740. $previous_db = tripal_db_set_active('chado'); // use chado database
  741. $resource = db_query($sql, $args);
  742. tripal_db_set_active($previous_db); // now use drupal database
  743. $results = array();
  744. while ($r = db_fetch_object($resource)) {
  745. $results[] = $r;
  746. }
  747. if (!$options['has_record']) {
  748. return $results;
  749. }
  750. else {
  751. return count($results);
  752. }
  753. }
  754. /**
  755. * Gets the value of a foreign key relationship
  756. *
  757. * This function is used by tripal_core_chado_select, tripal_core_chado_insert,
  758. * and tripal_core_chado_update to iterate through the associate array of
  759. * values that gets passed to each of those routines. The values array
  760. * is nested where foreign key contraints are used to specify a value that. See
  761. * documentation for any of those functions for further information.
  762. *
  763. * @param $table_desc
  764. * A table description for the table with the foreign key relationship to be identified generated by
  765. * hook_chado_<table name>_schema()
  766. * @param $field
  767. * The field in the table that is the foreign key.
  768. * @param $values
  769. * An associative array containing the values
  770. * @param $options
  771. * An associative array of additional options where the key is the option
  772. * and the value is the value of that option. These options are passed on to tripal_core_chado_select.
  773. *
  774. * Additional Options Include:
  775. * - case_insensitive_columns
  776. * An array of columns to do a case insensitive search on.
  777. * - regex_columns
  778. * An array of columns where the value passed in should be treated as a regular expression
  779. *
  780. * @return
  781. * A string containg the results of the foreign key lookup, or FALSE if failed.
  782. *
  783. * Example usage:
  784. * @code
  785. *
  786. * $values = array(
  787. * 'genus' => 'Citrus',
  788. * 'species' => 'sinensis',
  789. * );
  790. * $value = tripal_core_chado_get_foreign_key('feature', 'organism_id',$values);
  791. *
  792. * @endcode
  793. * The above code selects a record from the feature table using the three fields
  794. * that uniquely identify a feature. The $columns array simply lists the columns
  795. * to select. The $values array is nested such that the organism is identified by
  796. * way of the organism_id foreign key constraint by specifying the genus and
  797. * species. The cvterm is also specified using its foreign key and the cv_id
  798. * for the cvterm is nested as well.
  799. *
  800. * @ingroup tripal_chado_api
  801. */
  802. function tripal_core_chado_get_foreign_key($table_desc, $field, $values, $options = NULL) {
  803. if (!is_array($options)) {
  804. $options = array();
  805. }
  806. if (!$options['case_insensitive_columns']) {
  807. $options['case_insensitive_columns'] = array();
  808. }
  809. if (!$options['regex_columns']) {
  810. $options['regex_columns'] = array();
  811. }
  812. // get the list of foreign keys for this table description and
  813. // iterate through those until we find the one we're looking for
  814. $fkeys = $table_desc['foreign keys'];
  815. if ($fkeys) {
  816. foreach ($fkeys as $name => $def) {
  817. if (is_array($def['table'])) {
  818. //foreign key was described 2X
  819. $message = "The foreign key " . $name . " was defined twice. Please check modules "
  820. ."to determine if hook_chado_" . $table_desc['table'] . "_schema() was "
  821. ."implemented and defined this foreign key when it wasn't supposed to. Modules "
  822. ."this hook was implemented in: " . implode(', ',
  823. module_implements("chado_" . $table_desc['table'] . "_schema")) . ".";
  824. watchdog('tripal_core', $message);
  825. drupal_set_message(check_plain($message), 'error');
  826. continue;
  827. }
  828. $table = $def['table'];
  829. $columns = $def['columns'];
  830. // iterate through the columns of the foreign key relationship
  831. foreach ($columns as $left => $right) {
  832. // does the left column in the relationship match our field?
  833. if (strcmp($field, $left) == 0) {
  834. // the column name of the foreign key matches the field we want
  835. // so this is the right relationship. Now we want to select
  836. $select_cols = array($right);
  837. $result = tripal_core_chado_select($table, $select_cols, $values, $options);
  838. $fields = array();
  839. if (count($result) > 0) {
  840. foreach ($result as $obj) {
  841. $fields[] = $obj->$right;
  842. }
  843. return $fields;
  844. }
  845. }
  846. }
  847. }
  848. }
  849. else {
  850. // TODO: what do we do if we get to this point and we have a fk
  851. // relationship expected but we don't have any definition for one in the
  852. // table schema??
  853. $message = "There is no foreign key relationship defined for " . $field . ".
  854. To define a foreign key relationship, determine the table this foreign
  855. key referrs to (<foreign table>) and then implement
  856. hook_chado_<foreign table>_schema(). See
  857. tripal_feature_chado_feature_schema for an example.";
  858. watchdog('tripal_core', $message);
  859. drupal_set_message(check_plain($message), 'error');
  860. }
  861. return FALSE;
  862. }
  863. /**
  864. * Generates an object containing the full details of a record(s) in chado.
  865. *
  866. * This differs from the objects returned by tripal_core_chado_select in so far as all foreign key
  867. * relationships have been followed meaning you have more complete details. Thus this function
  868. * should be used whenever you need a full variable and tripal_core_chado_select should be used if
  869. * you only case about a few columns.
  870. *
  871. * @param $table
  872. * The name of the base table to generate a variable for
  873. * @param $values
  874. * A select values array that selects the records you want from the base table
  875. * (this has the same form as tripal_core_chado_select)
  876. * @param $base_options
  877. * An array containing options for the base table. For example, an
  878. * option of 'order_by' may be used to sort results in the base table
  879. * if more than one are returned. The options must be compatible with
  880. * the options accepted by the tripal_core_chado_select() function.
  881. * @return
  882. * Either an object (if only one record was selected from the base table)
  883. * or an array of objects (if more than one record was selected from the base table).
  884. *
  885. * Example Usage:
  886. * @code
  887. $values = array(
  888. 'name' => 'Medtr4g030710'
  889. );
  890. $features = tripal_core_generate_chado_var('feature', $values);
  891. * @endcode
  892. * This will return an object if there is only one feature with the name Medtr4g030710 or it will
  893. * return an array of feature objects if more than one feature has that name.
  894. *
  895. * Note to Module Designers: Fields can be excluded by default from these objects by implementing
  896. * one of the following hooks:
  897. * - hook_exclude_field_from_tablename_by_default (where tablename is the name of the table):
  898. * This hook allows you to add fields to be excluded on a per table basis. Simply implement
  899. * this hook to return an array of fields to be excluded. For example:
  900. * @code
  901. mymodule_exclude_field_from_feature_by_default() {
  902. return array('residues' => TRUE);
  903. }
  904. * @endcode
  905. * will ensure that feature.residues is ecluded from a feature object by default.
  906. * - hook_exclude_type_by_default:
  907. * This hook allows you to exclude fields from all tables that are of a given postgresql field
  908. * type. Simply implement this hook to return an array of postgresql types mapped to criteria.
  909. * Then all fields of that type where the criteria supplied returns TRUE will be excluded from
  910. * any table. Tokens available in criteria are &gt;field_value&lt; and &gt;field_name&lt; . For example:
  911. * @code
  912. mymodule_exclude_type_by_default() {
  913. return array('text' => 'length(&gt;field_value&lt; ) > 50');
  914. }
  915. * @endcode
  916. * 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.
  917. *
  918. * @ingroup tripal_chado_api
  919. */
  920. function tripal_core_generate_chado_var($table, $values, $base_options = array()) {
  921. $all = new stdClass();
  922. // get description for the current table----------------------------------------------------------
  923. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  924. $table_primary_key = $table_desc['primary key'][0];
  925. $table_columns = array_keys($table_desc['fields']);
  926. // Expandable fields without value needed for criteria--------------------------------------------
  927. $all->expandable_fields = array();
  928. if ($table_desc['referring_tables']) {
  929. $all->expandable_tables = $table_desc['referring_tables'];
  930. }
  931. else {
  932. $all->expandable_tables = array();
  933. }
  934. $all->expandable_nodes = array();
  935. // Get fields to be removed by name.................................
  936. $fields_to_remove = module_invoke_all('exclude_field_from_' . $table . '_by_default');
  937. foreach ($fields_to_remove as $field_name => $criteria) {
  938. //replace &gt;field_name&lt; with the current field name &
  939. $criteria = preg_replace('/&gt;field_name&lt; /', $field_name, $criteria);
  940. // if field_value needed we can't deal with this field yet
  941. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  942. break;
  943. }
  944. //if criteria then remove from query
  945. // @coder-ignore: only module designers can populate $criteria -not security risk
  946. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  947. // watchdog('tripal_core',
  948. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  949. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  950. // WATCHDOG_NOTICE
  951. // );
  952. if ($success) {
  953. unset($table_columns[array_search($field_name, $table_columns)]);
  954. unset($fields_to_remove[$field_name]);
  955. $all->expandable_fields[] = $table . '.' . $field_name;
  956. }
  957. }
  958. //Get fields to be removed by type................................
  959. $types_to_remove = module_invoke_all('exclude_type_by_default');
  960. $field_types = array();
  961. foreach ($table_desc['fields'] as $field_name => $field_array) {
  962. $field_types[$field_array['type']][] = $field_name;
  963. }
  964. foreach ($types_to_remove as $field_type => $criteria) {
  965. // if there are fields of that type to remove
  966. if (is_array($field_types[$field_type])) {
  967. //replace &gt;field_name&lt; with the current field name &
  968. $criteria = preg_replace('/&gt;field_name&lt; /', $field_name, $criteria);
  969. foreach ($field_types[$field_type] as $field_name) {
  970. // if field_value needed we can't deal with this field yet
  971. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  972. $fields_to_remove[$field_name] = $criteria;
  973. continue;
  974. }
  975. // if field_value needed we can't deal with this field yet
  976. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  977. break;
  978. }
  979. //if criteria then remove from query
  980. // @coder-ignore: only module designers can populate $criteria -not security risk
  981. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  982. // watchdog('tripal_core',
  983. // 'Evaluating criteria (%criteria) for field %field of $type in tripal_core_generate_chado_var for %table evaluated to %success',
  984. // array('%table'=>$table, '%criteria'=>$criteria, '%field'=>$field_name, '%type'=>$field_type, '%success'=>$success),
  985. // WATCHDOG_NOTICE
  986. // );
  987. if ($success) {
  988. unset($table_columns[array_search($field_name, $table_columns)]);
  989. $all->expandable_fields[] = $table . '.' . $field_name;
  990. }
  991. } //end of foreach field of that type
  992. }
  993. } //end of foreach type to be removed
  994. // get the values for the record in the current table---------------------------------------------
  995. $results = tripal_core_chado_select($table, $table_columns, $values, $base_options);
  996. if ($results) {
  997. foreach ($results as $key => $object) {
  998. // Add empty expandable_x arrays
  999. $object->expandable_fields = $all->expandable_fields;
  1000. $object->expandable_tables = $all->expandable_tables;
  1001. $object->expandable_nodes = $all->expandable_nodes;
  1002. // add curent table
  1003. $object->tablename = $table;
  1004. // check if the current table maps to a node type-----------------------------------------------
  1005. // if this table is connected to a node there will be a chado_tablename table in drupal
  1006. if (db_table_exists('chado_' . $table)) {
  1007. // that has a foreign key to this one ($table_desc['primary key'][0]
  1008. // and to the node table (nid)
  1009. // @coder-ignore: acting on chado schema rather then drupal schema therefore, table prefixing does not apply
  1010. $sql = "SELECT %s, nid FROM chado_%s WHERE %s=%d";
  1011. $mapping = db_fetch_object(db_query(
  1012. $sql,
  1013. $table_primary_key,
  1014. $table,
  1015. $table_primary_key,
  1016. $object->{$table_primary_key}
  1017. ));
  1018. if ($mapping->{$table_primary_key}) {
  1019. $object->nid = $mapping->nid;
  1020. $object->expandable_nodes[] = $table;
  1021. }
  1022. }
  1023. // remove any fields where criteria need to be evalulated---------------------------------------
  1024. foreach ($fields_to_remove as $field_name => $criteria) {
  1025. if (!isset($object->{$field_name})) {
  1026. break;
  1027. }
  1028. $criteria = preg_replace('/&gt;field_value&lt; /', $object->{$field_name}, $criteria);
  1029. //if criteria then remove from query
  1030. // @coder-ignore: only module designers can populate $criteria -not security risk
  1031. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  1032. // watchdog('tripal_core',
  1033. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  1034. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  1035. // WATCHDOG_NOTICE
  1036. // );
  1037. if ($success) {
  1038. unset($object->{$field_name});
  1039. $object->expandable_fields[] = $table . '.' . $field_name;
  1040. }
  1041. }
  1042. // recursively follow foreign key relationships nesting objects as we go------------------------
  1043. if ($table_desc['foreign keys']) {
  1044. foreach ($table_desc['foreign keys'] as $foreign_key_array) {
  1045. $foreign_table = $foreign_key_array['table'];
  1046. foreach ($foreign_key_array['columns'] as $foreign_key => $primary_key) {
  1047. // Note: Foreign key is the field in the current table whereas primary_key is the field in
  1048. // the table referenced by the foreign key
  1049. //Dont do anything if the foreign key is empty
  1050. if (empty($object->{$foreign_key})) {
  1051. break;
  1052. }
  1053. // get the record from the foreign table
  1054. $foreign_values = array($primary_key => $object->{$foreign_key});
  1055. $foreign_object = tripal_core_generate_chado_var($foreign_table, $foreign_values);
  1056. // add the foreign record to the current object in a nested manner
  1057. $object->{$foreign_key} = $foreign_object;
  1058. // Flatten expandable_x arrays so only in the bottom object
  1059. if (is_array($object->{$foreign_key}->expandable_fields)) {
  1060. $object->expandable_fields = array_merge(
  1061. $object->expandable_fields,
  1062. $object->{$foreign_key}->expandable_fields
  1063. );
  1064. unset($object->{$foreign_key}->expandable_fields);
  1065. }
  1066. if (is_array($object->{$foreign_key}->expandable_tables)) {
  1067. $object->expandable_tables = array_merge(
  1068. $object->expandable_tables,
  1069. $object->{$foreign_key}->expandable_tables
  1070. );
  1071. unset($object->{$foreign_key}->expandable_tables);
  1072. }
  1073. if (is_array($object->{$foreign_key}->expandable_nodes)) {
  1074. $object->expandable_nodes = array_merge(
  1075. $object->expandable_nodes,
  1076. $object->{$foreign_key}->expandable_nodes
  1077. );
  1078. unset($object->{$foreign_key}->expandable_nodes);
  1079. }
  1080. }
  1081. }
  1082. $results[$key] = $object;
  1083. }
  1084. }
  1085. }
  1086. // check only one result returned
  1087. if (sizeof($results) == 1) {
  1088. // add results to object
  1089. return $results[0];
  1090. }
  1091. elseif (!empty($results)) {
  1092. return $results;
  1093. }
  1094. else {
  1095. // no results returned
  1096. }
  1097. }
  1098. /**
  1099. * Retrieves fields/tables/nodes that were excluded by default from a variable and adds them
  1100. *
  1101. * This function exists to allow tripal_core_generate_chado_var() to excldue some
  1102. * fields/tables/nodes from the default form of a variable without making it extremely difficult for
  1103. * the tripal admin to get at these variables if he/she wants them.
  1104. *
  1105. * @param $object
  1106. * This must be an object generated using tripal_core_generate_chado_var()
  1107. * @param $type
  1108. * Must be one of 'field', 'table', 'node'. Indicates what is being expanded.
  1109. * @param $to_expand
  1110. * The name of the field/table/node to be expanded
  1111. * @param $table_options
  1112. * An array containing options for the base table. For example, an
  1113. * option of 'order_by' may be used to sort results in the base table
  1114. * if more than one are returned. The options must be compatible with
  1115. * the options accepted by the tripal_core_chado_select() function.
  1116. * @return
  1117. * A chado object supplemented with the field/table/node requested to be expanded
  1118. *
  1119. * Example Usage:
  1120. * @code
  1121. // Get a chado object to be expanded
  1122. $values = array(
  1123. 'name' => 'Medtr4g030710'
  1124. );
  1125. $features = tripal_core_generate_chado_var('feature', $values);
  1126. // Expand the organism node
  1127. $feature = tripal_core_expand_chado_vars($feature, 'node', 'organism');
  1128. // Expand the feature.residues field
  1129. $feature = tripal_core_expand_chado_vars($feature, 'field', 'feature.residues');
  1130. // Expand the feature properties (featureprop table)
  1131. $feature = tripal_core_expand_chado_vars($feature, 'table', 'featureprop');
  1132. * @endcode
  1133. *
  1134. * @ingroup tripal_chado_api
  1135. */
  1136. function tripal_core_expand_chado_vars($object, $type, $to_expand, $table_options = array()) {
  1137. $base_table = $object->tablename;
  1138. // check to see if they are expanding an array of objects
  1139. if (is_array($object)) {
  1140. foreach ($object as $index => $o) {
  1141. $object[$index] = tripal_core_expand_chado_vars($o, $type, $to_expand);
  1142. }
  1143. return $object;
  1144. }
  1145. switch ($type) {
  1146. case "field": //--------------------------------------------------------------------------------
  1147. if (preg_match('/(\w+)\.(\w+)/', $to_expand, $matches)) {
  1148. $tablename = $matches[1];
  1149. $fieldname = $matches[2];
  1150. $table_desc = module_invoke_all('chado_' . $tablename . '_schema');
  1151. $values = array();
  1152. foreach ($table_desc['primary key'] as $key) {
  1153. $values[$key] = $object->{$key};
  1154. }
  1155. if ($base_table == $tablename) {
  1156. //get the field
  1157. $results = tripal_core_chado_select(
  1158. $tablename,
  1159. array($fieldname),
  1160. $values
  1161. );
  1162. $object->{$fieldname} = $results[0]->{$fieldname};
  1163. $object->expanded = $to_expand;
  1164. }
  1165. else {
  1166. //We need to recurse -the field is in a nested object
  1167. foreach ((array) $object as $field_name => $field_value) {
  1168. if (is_object($field_value)) {
  1169. $object->{$field_name} = tripal_core_expand_chado_vars(
  1170. $field_value,
  1171. 'field',
  1172. $to_expand
  1173. );
  1174. }
  1175. } //end of for each field in the current object
  1176. }
  1177. }
  1178. else {
  1179. watchdog(
  1180. 'tripal_core',
  1181. 'tripal_core_expand_chado_vars: Field (%field) not in the right format. It should be <tablename>.<fieldname>',
  1182. WATCHDOG_ERROR
  1183. );
  1184. }
  1185. break;
  1186. case "table": //--------------------------------------------------------------------------------
  1187. $foreign_table = $to_expand;
  1188. $foreign_table_desc = module_invoke_all('chado_' . $foreign_table . '_schema');
  1189. // If it's connected to the base table
  1190. if ($foreign_table_desc['foreign keys'][$base_table]) {
  1191. foreach ($foreign_table_desc['foreign keys'][$base_table]['columns'] as $left => $right) {
  1192. if (!$object->{$right}) {
  1193. break;
  1194. }
  1195. if (is_array($values)) {
  1196. $values = array_merge($values, array($left => $object->{$right}) );
  1197. }
  1198. else {
  1199. $values = array($left => $object->{$right});
  1200. }
  1201. $foreign_object = tripal_core_generate_chado_var(
  1202. $foreign_table,
  1203. array($left => $object->{$right}),
  1204. $table_options
  1205. );
  1206. if ($foreign_object) {
  1207. // in the case where the foreign key relationships exists more
  1208. // than once with the same table we want to alter the
  1209. // array structure
  1210. if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
  1211. $object->{$foreign_table} = new stdClass();
  1212. $object->{$foreign_table}->{$left} = $foreign_object;
  1213. $object->expanded = $to_expand;
  1214. }
  1215. else {
  1216. $object->{$foreign_table} = $foreign_object;
  1217. $object->expanded = $to_expand;
  1218. }
  1219. }
  1220. }
  1221. }
  1222. else {
  1223. //We need to recurse -the table has a relationship to one of the nested objects
  1224. foreach ((array) $object as $field_name => $field_value) {
  1225. // if we have a nested object ->expand the table in it
  1226. if (is_object($field_value)) {
  1227. $object->{$field_name} = tripal_core_expand_chado_vars(
  1228. $field_value,
  1229. 'table',
  1230. $foreign_table
  1231. );
  1232. }
  1233. }
  1234. }
  1235. break;
  1236. case "node": //---------------------------------------------------------------------------------
  1237. //if the node to be expanded is for our base table, then just expand it
  1238. if ($object->tablename == $to_expand) {
  1239. $node = node_load($object->nid);
  1240. if ($node) {
  1241. $object->expanded = $to_expand;
  1242. $node->expandable_fields = $object->expandable_fields;
  1243. unset($object->expandable_fields);
  1244. $node->expandable_tables = $object->expandable_tables;
  1245. unset($object->expandable_tables);
  1246. $node->expandable_nodes = $object->expandable_nodes;
  1247. unset($object->expandable_nodes);
  1248. $node->{$base_table} = $object;
  1249. $object = $node;
  1250. }
  1251. else {
  1252. watchdog(
  1253. 'tripal_core',
  1254. 'tripal_core_expand_chado_vars: No node matches the nid (%nid) supplied.',
  1255. array('%nid' => $object->nid),
  1256. WATCHDOG_ERROR
  1257. );
  1258. } //end of if node
  1259. }
  1260. else {
  1261. //We need to recurse -the node to expand is one of the nested objects
  1262. foreach ((array) $object as $field_name => $field_value) {
  1263. if (is_object($field_value)) {
  1264. $object->{$field_name} = tripal_core_expand_chado_vars(
  1265. $field_value,
  1266. 'node',
  1267. $to_expand
  1268. );
  1269. }
  1270. } //end of for each field in the current object
  1271. }
  1272. break;
  1273. default:
  1274. watchdog('tripal_core',
  1275. 'tripal_core_expand_chado_vars: Unrecognized type (%type). Should be one of "field", "table", "node".',
  1276. array('%type' => $type),
  1277. WATCHDOG_ERROR
  1278. );
  1279. return FALSE;
  1280. }
  1281. //move extended array downwards-------------------------------------------------------------------
  1282. if (!$object->expanded) {
  1283. //if there's no extended field then go hunting for it
  1284. foreach ( (array)$object as $field_name => $field_value) {
  1285. if (is_object($field_value)) {
  1286. if (isset($field_value->expanded)) {
  1287. $object->expanded = $field_value->expanded;
  1288. unset($field_value->expanded);
  1289. }
  1290. }
  1291. }
  1292. }
  1293. //try again becasue now we might have moved it down
  1294. if ($object->expanded) {
  1295. $expandable_name = 'expandable_' . $type . 's';
  1296. if ($object->{$expandable_name}) {
  1297. $key_to_remove = array_search($object->expanded, $object->{$expandable_name});
  1298. unset($object->{$expandable_name}[$key_to_remove]);
  1299. unset($object->expanded);
  1300. }
  1301. else {
  1302. // if there is an expandable array then we've reached the base object
  1303. // if we get here and don't have anything expanded then something went wrong
  1304. // watchdog(
  1305. // 'tripal_core',
  1306. // 'tripal_core_expand_chado_vars: Unable to expand the %type %to_expand',
  1307. // array('%type'=>$type, '%to_expand'=>$to_expand),
  1308. // WATCHDOG_ERROR
  1309. // );
  1310. } //end of it we've reached the base object
  1311. }
  1312. return $object;
  1313. }
  1314. /**
  1315. * Implements hook_exclude_type_by_default()
  1316. *
  1317. * This hooks allows fields of a specified type that match a specified criteria to be excluded by
  1318. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1319. * fields are excluded by default they can always be expanded at a later date using
  1320. * tripal_core_expand_chado_vars().
  1321. *
  1322. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1323. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1324. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1325. * contain the following tokens:
  1326. * - &gt;field_name&lt;
  1327. * Replaced by the name of the field to be excluded
  1328. * - &gt;field_value&lt;
  1329. * Replaced by the value of the field in the current record
  1330. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1331. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1332. * query.
  1333. *
  1334. * @return
  1335. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1336. *
  1337. * @ingroup tripal_chado_api
  1338. */
  1339. function tripal_core_exclude_type_by_default() {
  1340. return array('text' => "strlen('&gt;field_value&lt; ') > 100");
  1341. }
  1342. /**
  1343. * Implements hook_exclude_field_from_<tablename>_by_default()
  1344. *
  1345. * This hooks allows fields from a specified table that match a specified criteria to be excluded by
  1346. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1347. * fields are excluded by default they can always be expanded at a later date using
  1348. * tripal_core_expand_chado_vars().
  1349. *
  1350. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1351. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1352. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1353. * contain the following tokens:
  1354. * - &gt;field_name&lt;
  1355. * Replaced by the name of the field to be excluded
  1356. * - &gt;field_value&lt;
  1357. * Replaced by the value of the field in the current record
  1358. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1359. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1360. * query.
  1361. *
  1362. * @return
  1363. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1364. *
  1365. * @ingroup tripal_chado_api
  1366. */
  1367. function tripal_core_exclude_field_from_feature_by_default() {
  1368. return array();
  1369. }
  1370. /**
  1371. * Use this function instead of db_query() to avoid switching databases
  1372. * when making query to the chado database
  1373. *
  1374. * Will use a chado persistent connection if it already exists
  1375. *
  1376. * @param $sql
  1377. * The sql statement to execute
  1378. */
  1379. function chado_query($sql) {
  1380. global $active_db;
  1381. $args = func_get_args();
  1382. array_shift($args);
  1383. $sql = db_prefix_tables($sql);
  1384. if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
  1385. $args = $args[0];
  1386. }
  1387. _db_query_callback($args, TRUE);
  1388. $sql = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $sql);
  1389. // Execute the query on the chado database/schema
  1390. // Use the persistent chado connection if it already exists
  1391. $persistent_connection = variable_get('tripal_perisistent_chado', NULL);
  1392. if ($persistent_connection) {
  1393. $previously_active_db = $active_db;
  1394. $active_db = $persistent_connection;
  1395. $results = _db_query($sql);
  1396. $active_db = $previously_active_db;
  1397. }
  1398. else {
  1399. $previous_db = tripal_db_set_active('chado');
  1400. $results = _db_query($sql);
  1401. tripal_db_set_active($previous_db);
  1402. }
  1403. return $results;
  1404. }
  1405. /**
  1406. * Get chado id for a node. E.g, if you want to get 'analysis_id' from the
  1407. * 'analysis' table for a synced 'chado_analysis' node, use:
  1408. * $analysis_id = chado_get_id_for_node ('analysis', $node)
  1409. * Likewise,
  1410. * $organism_id = chado_get_id_for_node ('organism', $node)
  1411. * $feature_id = chado_get_id_for_node ('feature', $node)
  1412. */
  1413. function chado_get_id_for_node($table, $node) {
  1414. return db_result(db_query("SELECT %s_id FROM {chado_%s} WHERE nid = %d", $table, $table, $node->nid));
  1415. }
  1416. /**
  1417. * Get node id for a chado feature/organism/analysis. E.g, if you want to
  1418. * get the node id for an analysis, use:
  1419. * $nid = chado_get_node_id ('analysis', $analysis_id)
  1420. * Likewise,
  1421. * $nid = chado_get_node_id ('organism', $organism_id)
  1422. * $nid = chado_get_node_id ('feature', $feature_id)
  1423. */
  1424. function chado_get_node_id($table, $id) {
  1425. return db_result(db_query("SELECT nid FROM {chado_%s} WHERE %s_id = %d", $table, $table, $id));
  1426. }
  1427. /**
  1428. * Retrieve a property for a given base table record
  1429. *
  1430. * @param $basetable
  1431. * The base table for which the property should be retrieved. Thus to retrieve a property
  1432. * for a feature the basetable=feature and property is retrieved from featureprop
  1433. * @param $record_id
  1434. * The foriegn key field of the base table. This should be in integer.
  1435. * @param $property
  1436. * The cvterm name describing the type of properties to be retrieved
  1437. * @param $cv_name
  1438. * The name of the cv that the above cvterm is part of
  1439. *
  1440. * @return
  1441. * An array in the same format as that generated by the function
  1442. * tripal_core_generate_chado_var(). If only one record is returned it
  1443. * is a single object. If more than one record is returned then it is an array
  1444. * of objects
  1445. *
  1446. * @ingroup tripal_chado_api
  1447. */
  1448. function tripal_core_get_property($basetable, $record_id, $property, $cv_name) {
  1449. // get the foreign key for this property table
  1450. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1451. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1452. // construct the array of values to be selected
  1453. $values = array(
  1454. $fkcol => $record_id,
  1455. 'type_id' => array(
  1456. 'cv_id' => array(
  1457. 'name' => $cv_name,
  1458. ),
  1459. 'name' => $property,
  1460. 'is_obsolete' => 0
  1461. ),
  1462. );
  1463. $results = tripal_core_generate_chado_var($basetable . 'prop', $values);
  1464. $results = tripal_core_expand_chado_vars($results, 'field', $basetable . 'prop.value');
  1465. return $results;
  1466. }
  1467. /**
  1468. * Insert a property for a given base table. By default if the property already
  1469. * exists a new property is added with the next available rank. If
  1470. * $update_if_present argument is specified then the record will be updated if it
  1471. * exists rather than adding a new property.
  1472. *
  1473. * @param $basetable
  1474. * The base table for which the property should be inserted. Thus to insert a property
  1475. * for a feature the basetable=feature and property is inserted into featureprop
  1476. * @param $record_id
  1477. * The foriegn key field of the base table. This should be in integer.
  1478. * @param $property
  1479. * The cvterm name describing the type of properties to be inserted
  1480. * @param $cv_name
  1481. * The name of the cv that the above cvterm is part of
  1482. * @param $value
  1483. * The value of the property to be inserted (can be empty)
  1484. * @param $update_if_present
  1485. * A boolean indicating whether an existing record should be updated. If the
  1486. * property already exists and this value is not specified or is zero then
  1487. * a new property will be added with the next largest rank.
  1488. *
  1489. * @return
  1490. * Return True on Insert/Update and False otherwise
  1491. *
  1492. * @ingroup tripal_chado_api
  1493. */
  1494. function tripal_core_insert_property($basetable, $record_id, $property,
  1495. $cv_name, $value, $update_if_present = 0) {
  1496. // first see if the property already exists, if the user want's to update
  1497. // then we can do that, but otherwise we want to increment the rank and
  1498. // insert
  1499. $props = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  1500. if (!is_array($props)) {
  1501. $props = array($props);
  1502. }
  1503. $rank = 0;
  1504. if (count($props)>0) {
  1505. if ($update_if_present) {
  1506. return tripal_core_update_property($basetable, $record_id, $property, $cv_name, $value);
  1507. }
  1508. else {
  1509. // iterate through the properties returned and check to see if the
  1510. // property with this value already exists if not, get the largest rank
  1511. // and insert the same property but with this new value
  1512. foreach ($props as $p) {
  1513. if ($p->rank > $rank) {
  1514. $rank = $p->rank;
  1515. }
  1516. if (strcmp($p->value, $value) == 0) {
  1517. return TRUE;
  1518. }
  1519. }
  1520. // now add 1 to the rank
  1521. $rank++;
  1522. }
  1523. }
  1524. // get the foreign key for this property table
  1525. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1526. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1527. // construct the array of values to be inserted
  1528. $values = array(
  1529. $fkcol => $record_id,
  1530. 'type_id' => array(
  1531. 'cv_id' => array(
  1532. 'name' => $cv_name,
  1533. ),
  1534. 'name' => $property,
  1535. 'is_obsolete' => 0
  1536. ),
  1537. 'value' => $value,
  1538. 'rank' => $rank,
  1539. );
  1540. return tripal_core_chado_insert($basetable . 'prop', $values);
  1541. }
  1542. /**
  1543. * Update a property for a given base table record and property name. This
  1544. * function should be used only if one record of the property will be present.
  1545. * If the property name can have multiple entries (with increasing rank) then
  1546. * use the function named tripal_core_update_property_by_id
  1547. *
  1548. * @param $basetable
  1549. * The base table for which the property should be updated. The property table
  1550. * is constructed using a combination of the base table name and the suffix
  1551. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  1552. * @param $record_id
  1553. * The foreign key of the basetable to update a property for. This should be in integer.
  1554. * For example, if the basetable is 'feature' then the $record_id should be the feature_id
  1555. * @param $property
  1556. * The cvterm name of property to be updated
  1557. * @param $cv_name
  1558. * The name of the cv that the above cvterm is part of
  1559. * @param $value
  1560. * The value of the property to be inserted (can be empty)
  1561. * @param $insert_if_missing
  1562. * A boolean indicating whether a record should be inserted if one doesn't exist to update
  1563. *
  1564. * Note: The property to be updated is select via the unique combination of $record_id and
  1565. * $property and then it is updated with the supplied value
  1566. *
  1567. * @return
  1568. * Return True on Update/Insert and False otherwise
  1569. *
  1570. * @ingroup tripal_chado_api
  1571. */
  1572. function tripal_core_update_property($basetable, $record_id, $property,
  1573. $cv_name, $value, $insert_if_missing = 0) {
  1574. // first see if the property is missing (we can't update a missing property
  1575. $prop = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  1576. if (count($prop)==0) {
  1577. if ($insert_if_missing) {
  1578. return tripal_core_insert_property($basetable, $record_id, $property, $cv_name, $value);
  1579. }
  1580. else {
  1581. return FALSE;
  1582. }
  1583. }
  1584. // get the foreign key for this property table
  1585. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1586. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1587. // construct the array that will match the exact record to update
  1588. $match = array(
  1589. $fkcol => $record_id,
  1590. 'type_id' => array(
  1591. 'cv_id' => array(
  1592. 'name' => $cv_name,
  1593. ),
  1594. 'name' => $property,
  1595. ),
  1596. );
  1597. // construct the array of values to be updated
  1598. $values = array(
  1599. 'value' => $value,
  1600. );
  1601. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  1602. }
  1603. /**
  1604. * Update a property for a given base table record. This function should be
  1605. * used if multiple records of the same property will be present. Also, use this
  1606. * function to change the property name of an existing property.
  1607. *
  1608. * @param $basetable
  1609. * The base table for which the property should be updated. The property table
  1610. * is constructed using a combination of the base table name and the suffix
  1611. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  1612. * @param $record_id
  1613. * The primary key of the base table. This should be in integer.
  1614. * For example, if the basetable is 'feature' then the $record_id should be the featureprop_id
  1615. * @param $property
  1616. * The cvterm name of property to be updated
  1617. * @param $cv_name
  1618. * The name of the cv that the above cvterm is part of
  1619. * @param $value
  1620. * The value of the property to be inserted (can be empty)
  1621. *
  1622. * @return
  1623. * Return True on Update/Insert and False otherwise
  1624. *
  1625. * @ingroup tripal_chado_api
  1626. */
  1627. function tripal_core_update_property_by_id($basetable, $record_id, $property,
  1628. $cv_name, $value) {
  1629. // get the primary key for this property table
  1630. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1631. $pkcol = $table_desc['primary key'][0];
  1632. // construct the array that will match the exact record to update
  1633. $match = array(
  1634. $pkcol => $record_id,
  1635. );
  1636. // construct the array of values to be updated
  1637. $values = array(
  1638. 'type_id' => array(
  1639. 'cv_id' => array(
  1640. 'name' => $cv_name,
  1641. ),
  1642. 'name' => $property,
  1643. ),
  1644. 'value' => $value,
  1645. );
  1646. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  1647. }
  1648. /**
  1649. * Deletes a property for a given base table record using the property name
  1650. *
  1651. * @param $basetable
  1652. * The base table for which the property should be deleted. Thus to deleted a property
  1653. * for a feature the basetable=feature and property is deleted from featureprop
  1654. * @param $record_id
  1655. * The primary key of the basetable to delete a property for. This should be in integer.
  1656. * @param $property
  1657. * The cvterm name describing the type of property to be deleted
  1658. * @param $cv_name
  1659. * The name of the cv that the above cvterm is part of
  1660. *
  1661. * Note: The property to be deleted is select via the unique combination of $record_id and $property
  1662. *
  1663. * @return
  1664. * Return True on Delete and False otherwise
  1665. *
  1666. * @ingroup tripal_chado_api
  1667. */
  1668. function tripal_core_delete_property($basetable, $record_id, $property, $cv_name) {
  1669. // get the foreign key for this property table
  1670. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1671. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1672. // construct the array that will match the exact record to update
  1673. $match = array(
  1674. $fkcol => $record_id,
  1675. 'type_id' => array(
  1676. 'cv_id' => array(
  1677. 'name' => $cv_name,
  1678. ),
  1679. 'name' => $property,
  1680. ),
  1681. );
  1682. return tripal_core_chado_delete($basetable . 'prop', $match);
  1683. }
  1684. /**
  1685. * Deletes a property using the property ID
  1686. *
  1687. * @param $basetable
  1688. * The base table for which the property should be deleted. Thus to deleted a property
  1689. * for a feature the basetable=feature and property is deleted from featureprop
  1690. * @param $record_id
  1691. * The primary key of the basetable to delete a property for. This should be in integer.
  1692. *
  1693. * @return
  1694. * Return True on Delete and False otherwise
  1695. *
  1696. * @ingroup tripal_chado_api
  1697. */
  1698. function tripal_core_delete_property_by_id($basetable, $record_id) {
  1699. // get the foreign key for this property table
  1700. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1701. $pkcol = $table_desc['primary key'][0];
  1702. // construct the array that will match the exact record to update
  1703. $match = array(
  1704. $pkcol => $record_id,
  1705. );
  1706. return tripal_core_chado_delete($basetable . 'prop', $match);
  1707. }
  1708. /**
  1709. * This function is typically used in the '.install' file for a Tripal module
  1710. * Each module should call this function during installation to create
  1711. * the module data directory which is sites/default/files/tripal/[module_name]
  1712. * for default Drupal settings. This directory can then be used by the module
  1713. * for storing files.
  1714. *
  1715. * @param $module_name
  1716. * the name of the module being installed.
  1717. *
  1718. * @returns
  1719. * nothing
  1720. *
  1721. * @ingroup tripal_files_api
  1722. */
  1723. function tripal_create_moddir($module_name) {
  1724. // make the data directory for this module
  1725. $data_dir = file_directory_path() . "/tripal/$module_name";
  1726. if (!file_check_directory($data_dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
  1727. $message = "Cannot create directory $data_dir. This module may not ".
  1728. "behave correctly without this directory. Please create ".
  1729. "the directory manually or fix the problem and reinstall.";
  1730. drupal_set_message(check_plain(t($message)), 'error');
  1731. watchdog('tripal_core', $message, array(), WATCHDOG_ERROR);
  1732. }
  1733. }
  1734. /**
  1735. * Each Tripal module has a unique data directory which was creatd using the
  1736. * tripal_create_moddir function during installation. This function
  1737. * retrieves the directory path.
  1738. *
  1739. * @param $module_name
  1740. * The name of the module
  1741. *
  1742. * @returns
  1743. * The path within the Drupal installation where the data directory resides
  1744. * @ingroup tripal_files_api
  1745. */
  1746. function tripal_get_moddir($module_name) {
  1747. $data_dir = file_directory_path() . "/tripal/$module_name";
  1748. return $data_dir;
  1749. }
  1750. /**
  1751. * Set the Tripal Database
  1752. *
  1753. * The tripal_db_set_active function is used to prevent namespace collisions
  1754. * when chado and drupal are installed in the same database but in different
  1755. * schemas. It is also used for backwards compatibility with older versions
  1756. * of tripal or in cases where chado is located outside of the Drupal database.
  1757. *
  1758. * @ingroup tripal_chado_api
  1759. */
  1760. function tripal_db_set_active($dbname) {
  1761. global $db_url, $db_type;
  1762. $chado_exists = 0;
  1763. // only postgres can support search paths. So if this is MysQL then
  1764. // just run the normal tripal_db_set_active function.
  1765. if (strcmp($db_type, 'pgsql')==0) {
  1766. // if the 'chado' database is in the $db_url variable then chado is
  1767. // not in the same Drupal database
  1768. if (is_array($db_url)) {
  1769. if (isset($db_url[$dbname])) {
  1770. return db_set_active($dbname);
  1771. }
  1772. }
  1773. // check to make sure the chado schema exists
  1774. $chado_exists = tripal_core_chado_schema_exists();
  1775. // here we make the assumption that the default database schema is
  1776. // 'public'. This will most likely always be the case but if not,
  1777. // then this code will break
  1778. if ($chado_exists && strcmp($dbname, 'chado')==0) {
  1779. db_query("set search_path to %s", 'chado,public');
  1780. return 'public,chado';
  1781. }
  1782. elseif ($chado_exists) {
  1783. db_query("set search_path to %s", 'public,chado');
  1784. return 'chado,public';
  1785. }
  1786. else {
  1787. return db_set_active($dbname);
  1788. }
  1789. }
  1790. else {
  1791. return db_set_active($dbname);
  1792. }
  1793. }
  1794. /**
  1795. * Instantiate or Return a persistent chado connection
  1796. *
  1797. * NOTE: cannot use $active_db since a new connection is created each time
  1798. * db_set_active() is called
  1799. *
  1800. * @return
  1801. * A postgresql connection object which can be used by pg_prepare, pg_execute, etc.
  1802. */
  1803. function tripal_db_persistent_chado() {
  1804. global $db_url;
  1805. // get connection if it already exists
  1806. $connection = variable_get('tripal_perisistent_chado', NULL);
  1807. if ($connection) {
  1808. return $connection;
  1809. // Otherwise we need to set it
  1810. }
  1811. else {
  1812. if (is_array($db_url) && isset($db_url['chado'])) {
  1813. $connection = db_connect($db_url['chado']);
  1814. variable_set('tripal_perisistent_chado', $connection);
  1815. }
  1816. else {
  1817. $connection = db_connect($db_url);
  1818. variable_set('tripal_perisistent_chado', $connection);
  1819. }
  1820. return $connection;
  1821. }
  1822. return FALSE;
  1823. }
  1824. /**
  1825. * Release a persistent chado connection
  1826. */
  1827. function tripal_db_release_persistent_chado() {
  1828. variable_del('tripal_perisistent_chado');
  1829. }
  1830. /**
  1831. * Start a transaction block. Ensures the use of a persistent chado connection
  1832. */
  1833. function tripal_db_start_transaction() {
  1834. $connection = tripal_db_persistent_chado();
  1835. chado_query("BEGIN");
  1836. }
  1837. /**
  1838. * Set a savepoint to roll the current transaction back to if an error is encountered
  1839. */
  1840. function tripal_db_set_savepoint_transaction($savepoint, $release = FALSE) {
  1841. // Postgresql requires a savepoint of the same name to be unset before re-use
  1842. if ($release) {
  1843. chado_query("RELEASE SAVEPOINT %s", $savepoint);
  1844. }
  1845. chado_query("SAVEPOINT %s", $savepoint);
  1846. }
  1847. /**
  1848. * Commit changes made during the current transaction
  1849. */
  1850. function tripal_db_commit_transaction() {
  1851. chado_query("COMMIT");
  1852. }
  1853. /**
  1854. * Rollback changes.
  1855. *
  1856. * If $savepoint is NULL then rollback to the beginning of the transaction,
  1857. * Otherwise, rollback to the point at which the named $savepoint was created
  1858. *
  1859. * @param $savepoint
  1860. * The name of the saved point in the transaction to rollback to
  1861. */
  1862. function tripal_db_rollback_transaction($savepoint = NULL, $commit = TRUE) {
  1863. if ($savepoint) {
  1864. chado_query("ROLLBACK TO SAVEPOINT %s", $savepoint);
  1865. }
  1866. else {
  1867. chado_query("ROLLBACK");
  1868. }
  1869. if ($commit) {
  1870. tripal_db_commit_transaction();
  1871. }
  1872. }
  1873. /**
  1874. * Purpose: Get max rank for a given set of criteria
  1875. * This function was developed with the many property tables in chado in mind
  1876. *
  1877. * @param $tablename
  1878. * The name of the chado table you want to select the max rank from this table must contain a
  1879. * rank column of type integer
  1880. * @param $where_options
  1881. * where options should include the id and type for that table to correctly
  1882. * group a set of records together where the only difference are the value and rank
  1883. * @code
  1884. * array(
  1885. * <column_name> => array(
  1886. * 'type' => <type of column: INT/STRING>,
  1887. * 'value' => <the value you want to filter on>,
  1888. * 'exact' => <if TRUE use =; if FALSE use ~>,
  1889. * )
  1890. * )
  1891. * @endcode
  1892. * @return the maximum rank
  1893. *
  1894. * @ingroup tripal_chado_api
  1895. */
  1896. function tripal_get_max_chado_rank($tablename, $where_options) {
  1897. $where= array();
  1898. //generate the where clause from supplied options
  1899. // the key is the column name
  1900. foreach ($where_options as $key => $val_array) {
  1901. if (preg_match('/INT/', $val_array['type'])) {
  1902. $where[] = $key . "=" . $val_array['value'];
  1903. }
  1904. else {
  1905. if ($val_array['exact']) {
  1906. $operator='=';
  1907. }
  1908. else {
  1909. $operator='~';
  1910. }
  1911. $where[] = $key . $operator . "'" . $val_array['value'] . "'";
  1912. }
  1913. }
  1914. $previous_db = tripal_db_set_active('chado');
  1915. $result = db_fetch_object(db_query(
  1916. "SELECT max(rank) as max_rank, count(rank) as count FROM %s WHERE %s",
  1917. $tablename,
  1918. implode(' AND ', $where)
  1919. ));
  1920. tripal_db_set_active($previous_db);
  1921. //drupal_set_message("Max Rank Query=SELECT max(rank) as max_rank, count(rank) as count FROM ".$tablename." WHERE ".implode(' AND ',$where));
  1922. if ($result->count > 0) {
  1923. return $result->max_rank;
  1924. }
  1925. else {
  1926. return -1;
  1927. }
  1928. }
  1929. /**
  1930. * Add a new table to the Chado schema. This function is simply a wrapper for
  1931. * the db_create_table() function of Drupal, but ensures the table is created
  1932. * inside the Chado schema rather than the Drupal schema. If the table already
  1933. * exists then it will be dropped and recreated using the schema provided.
  1934. * Howver, it will only drop a table if it exsits in the tripal_custom_tables
  1935. * table. This way the function cannot be used to accidentally alter existing
  1936. * non custom tables.
  1937. *
  1938. * @param $ret
  1939. * Array to which query results will be added.
  1940. * @param $table
  1941. * The name of the table to create.
  1942. * @param $schema
  1943. * A Drupal-style Schema API definition of the table
  1944. *
  1945. * @return
  1946. * A database query result resource for the new table, or FALSE if table was not constructed.
  1947. *
  1948. * @ingroup tripal_core_api
  1949. */
  1950. function tripal_create_chado_table(&$ret, $table, $schema) {
  1951. $ret = array();
  1952. // If the table exits in Chado but not in the tripal_custom_tables field
  1953. // then call an error. if the table exits in the tripal_custom_tables but
  1954. // not in Chado then create the table and replace the entry.
  1955. $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_name = '%s'";
  1956. $centry = db_fetch_object(db_query($sql, $table));
  1957. $previous_db = tripal_db_set_active('chado'); // use chado database
  1958. $exists = db_table_exists($table);
  1959. tripal_db_set_active($previous_db); // now use drupal database
  1960. if (!$exists) {
  1961. $previous_db = tripal_db_set_active('chado'); // use chado database
  1962. db_create_table($ret, $table, $schema);
  1963. tripal_db_set_active($previous_db); // now use drupal database
  1964. if (count($ret)==0) {
  1965. watchdog('tripal_core', "Error adding custom table '!table_name'.",
  1966. array('!table_name' => $table), WATCHDOG_ERROR);
  1967. return FALSE;
  1968. }
  1969. }
  1970. if ($exists and !$centry) {
  1971. watchdog('tripal_core', "Could not add custom table '!table_name'. It ".
  1972. "already exists but is not known to Tripal as being a custom table.",
  1973. array('!table_name' => $table), WATCHDOG_WARNING);
  1974. return FALSE;
  1975. }
  1976. if ($exists and $centry) {
  1977. // drop the table we'll recreate it with the new schema
  1978. $previous_db = tripal_db_set_active('chado'); // use chado database
  1979. db_drop_table($ret, $table);
  1980. db_create_table($ret, $table, $schema);
  1981. tripal_db_set_active($previous_db); // now use drupal database
  1982. }
  1983. // if the table creation was succesful then add an entry
  1984. // in the tripal_custom_table
  1985. $record = new stdClass();
  1986. $record->table_name = $table;
  1987. $record->schema = serialize($schema);
  1988. // if an entry already exists then remove it
  1989. if ($centry) {
  1990. $sql = "DELETE FROM {tripal_custom_tables} WHERE table_name = '%s'";
  1991. db_query($sql, $table);
  1992. }
  1993. $success = drupal_write_record('tripal_custom_tables', $record);
  1994. if (!$success) {
  1995. watchdog('tripal_core', "Error adding custom table.",
  1996. array('!table_name' => $table), WATCHDOG_ERROR);
  1997. return FALSE;
  1998. }
  1999. return $ret;
  2000. }
  2001. /**
  2002. * Retrieves the schema in an array for the specified custom table.
  2003. *
  2004. * @param $table
  2005. * The name of the table to create.
  2006. *
  2007. * @return
  2008. * A Drupal-style Schema API array definition of the table. Returns
  2009. * FALSE on failure.
  2010. *
  2011. * @ingroup tripal_core_api
  2012. */
  2013. function tripal_get_chado_custom_schema($table) {
  2014. $sql = "SELECT schema FROM {tripal_custom_tables} WHERE table_name = '%s'";
  2015. $custom = db_fetch_object(db_query($sql, $table));
  2016. if (!$custom) {
  2017. return FALSE;
  2018. }
  2019. else {
  2020. return unserialize($custom->schema);
  2021. }
  2022. }
  2023. /**
  2024. * Check that the Chado schema exists
  2025. *
  2026. * @return
  2027. * TRUE/FALSE depending upon whether it exists
  2028. */
  2029. function tripal_core_chado_schema_exists() {
  2030. // This is postgresql-specific code to check the existence of the chado schema
  2031. // @coder-ignore: acting on pg_catalog schema rather then drupal schema therefore, table prefixing does not apply
  2032. $sql = "SELECT nspname FROM pg_catalog.pg_namespace WHERE nspname = 'chado'";
  2033. if (db_fetch_object(db_query($sql))) {
  2034. return TRUE;
  2035. }
  2036. else {
  2037. return FALSE;
  2038. }
  2039. }