tripal_chado.db.api.inc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. <?php
  2. /**
  3. * @file
  4. * Provides an application programming interface (API) to manage references to
  5. * external databases
  6. */
  7. /**
  8. * @defgroup tripal_chado_api Database Reference API
  9. * @ingroup tripal_api
  10. * @{
  11. * Provides an application programming interface (API) to manage references to external databases
  12. * @}
  13. */
  14. /**
  15. * Retrieves a chado db variable
  16. *
  17. * Example Usage:
  18. * @code
  19. $select_values = array(
  20. 'name' => 'SOFP'
  21. );
  22. $db_object = tripal_get_db($select_values);
  23. * @endcode
  24. * The above code selects the SOFP db and returns the following object:
  25. * @code
  26. $db_object = stdClass Object (
  27. [db_id] => 49
  28. [name] => SOFP
  29. [description] =>
  30. [urlprefix] =>
  31. [url] =>
  32. );
  33. * @endcode
  34. *
  35. * @param $identifier
  36. * An array with the key stating what the identifier is. Supported keys (only on of the
  37. * following unique keys is required):
  38. * - db_id: the chado db.db_id primary key
  39. * - name: the chado db.name field (assume unique)
  40. * @param $options
  41. * An array of options. Supported keys include:
  42. * - Any keys supported by chado_generate_var(). See that function definition for
  43. * additional details.
  44. *
  45. * NOTE: the $identifier parameter can really be any array similar to $values passed into
  46. * chado_select_record(). It should fully specify the db record to be returned.
  47. *
  48. * @return
  49. * If unique values were passed in as an identifier then an object describing the cv
  50. * will be returned (will be a chado variable from chado_generate_var()). Otherwise,
  51. * an array of objects will be returned.
  52. *
  53. * @ingroup tripal_chado_api
  54. */
  55. function tripal_get_db($identifiers, $options = array()) {
  56. // Set Defaults
  57. if (!isset($options['include_fk'])) {
  58. // Tells chado_generate_var not to follow any foreign keys
  59. $options['include_fk'] = array();
  60. }
  61. // Error Checking of parameters
  62. if (!is_array($identifiers)) {
  63. tripal_report_error(
  64. 'tripal_chado_api',
  65. TRIPAL_ERROR,
  66. "tripal_get_db: The identifier passed in is expected to be an array with the key
  67. matching a column name in the db table (ie: db_id or name). You passed in %identifier.",
  68. array(
  69. '%identifier'=> print_r($identifiers, TRUE)
  70. )
  71. );
  72. }
  73. elseif (empty($identifiers)) {
  74. tripal_report_error(
  75. 'tripal_chado_api',
  76. TRIPAL_ERROR,
  77. "tripal_get_db: You did not pass in anything to identify the db you want. The identifier
  78. is expected to be an array with the key matching a column name in the db table
  79. (ie: db_id or name). You passed in %identifier.",
  80. array(
  81. '%identifier'=> print_r($identifiers, TRUE)
  82. )
  83. );
  84. }
  85. // Try to get the db
  86. $db = chado_generate_var(
  87. 'db',
  88. $identifiers,
  89. $options
  90. );
  91. // Ensure the db is singular. If it's an array then it is not singular
  92. if (is_array($db)) {
  93. tripal_report_error(
  94. 'tripal_chado_api',
  95. TRIPAL_ERROR,
  96. "tripal_get_db: The identifiers you passed in were not unique. You passed in %identifier.",
  97. array(
  98. '%identifier'=> print_r($identifiers, TRUE)
  99. )
  100. );
  101. }
  102. // Report an error if $db is FALSE since then chado_generate_var has failed
  103. elseif ($db === FALSE) {
  104. tripal_report_error(
  105. 'tripal_chado_api',
  106. TRIPAL_ERROR,
  107. "tripal_get_db: chado_generate_var() failed to return a db based on the identifiers
  108. you passed in. You should check that your identifiers are correct, as well as, look
  109. for a chado_generate_var error for additional clues. You passed in %identifier.",
  110. array(
  111. '%identifier'=> print_r($identifiers, TRUE)
  112. )
  113. );
  114. }
  115. // Else, as far we know, everything is fine so give them their db :)
  116. else {
  117. return $db;
  118. }
  119. }
  120. /**
  121. * Create an options array to be used in a form element
  122. * which provides a list of all chado dbs
  123. *
  124. * @return
  125. * An array(db_id => name) for each db in the chado db table
  126. *
  127. * @ingroup tripal_chado_api
  128. */
  129. function tripal_get_db_select_options() {
  130. $dbs = chado_query("SELECT db_id, name FROM {db} ORDER BY name");
  131. $options = array();
  132. $options[] = 'Select a Database';
  133. foreach ($dbs as $db) {
  134. $options[$db->db_id] = $db->name;
  135. }
  136. return $options;
  137. }
  138. /**
  139. * Retrieves a chado database reference variable
  140. *
  141. * Example Usage:
  142. * @code
  143. $identifiers = array(
  144. 'accession' => 'synonym',
  145. 'db_id' => array(
  146. 'name' => 'SOFP'
  147. )
  148. );
  149. $dbxref_object = tripal_get_dbxref($identifiers);
  150. * @endcode
  151. * The above code selects the synonym database reference and returns the following object:
  152. * @code
  153. $dbxref_object = stdClass Object (
  154. [dbxref_id] => 2581
  155. [accession] => synonym
  156. [description] =>
  157. [version] =>
  158. [db_db_id] => 49
  159. [db_name] => SOFP
  160. [db_description] =>
  161. [db_urlprefix] =>
  162. [db_url] =>
  163. );
  164. * @endcode
  165. *
  166. * @param $identifier
  167. * An array with the key stating what the identifier is. Supported keys (only one of the
  168. * following unique keys is required):
  169. * - dbxref_id: the chado dbxref.dbxref_id primary key
  170. * - accession: the chado dbxref.accession field (assume unique)
  171. * There are also some specially handled keys. They are:
  172. * - property: An array/object describing the property to select records for. It
  173. * should at least have either a type_name (if unique across cvs) or type_id. Other
  174. * supported keys include: cv_id/cv_name (of the type), value and rank
  175. * @param $options
  176. * An array of options. Supported keys include:
  177. * - Any keys supported by chado_generate_var(). See that function definition for
  178. * additional details.
  179. *
  180. * NOTE: the $identifier parameter can really be any array similar to $values passed into
  181. * chado_select_record(). It should fully specify the dbxref record to be returned.
  182. *
  183. * @return
  184. * If unique values were passed in as an identifier then an object describing the dbxref
  185. * will be returned (will be a chado variable from chado_generate_var()). Otherwise,
  186. * FALSE will be returned.
  187. *
  188. * @ingroup tripal_chado_api
  189. */
  190. function tripal_get_dbxref($identifiers, $options = array()) {
  191. // Set Defaults
  192. if (!isset($options['include_fk'])) {
  193. // Tells chado_generate_var not only expand the db
  194. $options['include_fk'] = array('db_id' => TRUE);
  195. }
  196. // Error Checking of parameters
  197. if (!is_array($identifiers)) {
  198. tripal_report_error(
  199. 'tripal_chado_api',
  200. TRIPAL_ERROR,
  201. "tripal_get_dbxref: The identifier passed in is expected to be an array with the key
  202. matching a column name in the dbxref table (ie: dbxref_id or name). You passed in %identifier.",
  203. array(
  204. '%identifier'=> print_r($identifiers, TRUE)
  205. )
  206. );
  207. }
  208. elseif (empty($identifiers)) {
  209. tripal_report_error(
  210. 'tripal_chado_api',
  211. TRIPAL_ERROR,
  212. "tripal_get_dbxref: You did not pass in anything to identify the dbxref you want. The identifier
  213. is expected to be an array with the key matching a column name in the dbxref table
  214. (ie: dbxref_id or name). You passed in %identifier.",
  215. array(
  216. '%identifier'=> print_r($identifiers, TRUE)
  217. )
  218. );
  219. }
  220. // If one of the identifiers is property then use chado_get_record_with_property()
  221. if (isset($identifiers['property'])) {
  222. $property = $identifiers['property'];
  223. unset($identifiers['property']);
  224. $dbxref = chado_get_record_with_property(
  225. array('table' => 'dbxref', 'base_records' => $identifiers),
  226. array('type_name' => $property),
  227. $options
  228. );
  229. }
  230. // Else we have a simple case and we can just use chado_generate_var to get the analysis
  231. else {
  232. $dbxref = chado_generate_var('dbxref', $identifiers, $options);
  233. }
  234. // Ensure the dbxref is singular. If it's an array then it is not singular
  235. if (is_array($dbxref)) {
  236. tripal_report_error('tripal_chado_api', TRIPAL_ERROR,
  237. "tripal_get_dbxref: The identifiers you passed in were not unique. You passed in %identifier.",
  238. array('%identifier'=> print_r($identifiers, TRUE))
  239. );
  240. }
  241. // Report an error if $dbxref is FALSE since then chado_generate_var has failed
  242. elseif ($dbxref === FALSE) {
  243. tripal_report_error(
  244. 'tripal_chado_api',
  245. TRIPAL_ERROR,
  246. "tripal_get_dbxref: chado_generate_var() failed to return a dbxref based on the identifiers
  247. you passed in. You should check that your identifiers are correct, as well as, look
  248. for a chado_generate_var error for additional clues. You passed in %identifier.",
  249. array(
  250. '%identifier'=> print_r($identifiers, TRUE)
  251. )
  252. );
  253. }
  254. // Else, as far we know, everything is fine so give them their dbxref :)
  255. else {
  256. return $dbxref;
  257. }
  258. }
  259. /**
  260. * Generates a URL for the controlled vocabulary term.
  261. *
  262. * If the URL and URL prefix are provided for the database record of a cvterm
  263. * then a URL can be created for the term. By default, the db.name and
  264. * dbxref.accession are concatenated and appended to the end of the db.urlprefix.
  265. * But Tripal supports the use of {db} and {accession} tokens when if present
  266. * in the db.urlprefix string will be replaced with the db.name and
  267. * dbxref.accession respectively.
  268. *
  269. * @param $dbxref
  270. * A dbxref object as created by the chado_generate_var() function.
  271. *
  272. * @return
  273. * A string containing the URL.
  274. */
  275. function tripal_get_dbxref_url($dbxref) {
  276. $final_url = '';
  277. // Create the URL for the term.
  278. if ($dbxref->db_id->urlprefix) {
  279. $db_count = 0;
  280. $acc_count = 0;
  281. $url = $dbxref->db_id->urlprefix;
  282. // If the URL prefix has replacement tokens then use those.
  283. $url = preg_replace('/\{db\}/', $dbxref->db_id->name, $url, -1, $db_count);
  284. $url = preg_replace('/\{accession\}/', $dbxref->accession, $url, -1, $acc_count);
  285. $final_url = $url;
  286. // If no replacements were made above then tokens weren't used and we can
  287. // default to just appending the db name and accession to the end.
  288. if (!$db_count and !$acc_count) {
  289. $final_url .= $dbxref->db_id->name . ':' . $dbxref->accession;
  290. }
  291. // If the URL prefix is relative then convert it to a full URL.
  292. if (!preg_match('/^(http|https)/', $final_url)) {
  293. $final_url = url($final_url, array('absolute' => TRUE));
  294. }
  295. }
  296. return $final_url;
  297. }
  298. /**
  299. * Adds a new database to the Chado DB table and returns the DB object.
  300. *
  301. * @param $values
  302. * An associative array of the values of the db (those to be inserted)
  303. * - name: The name of the database. This name is usually used as the prefix for
  304. * CV term accessions
  305. * - description: (Optional) A description of the database. By default no description is required.
  306. * - url: (Optional) The URL for the database
  307. * - urlprefix: (Optional) The URL that is to be used as a prefix when constructing a
  308. * link to a database term
  309. * @param $options
  310. * Optional. An associative array of options that can include:
  311. * - update_existing: Set this to '1' to force an update of the database if it
  312. * already exists. The default is to not update. If the database exists
  313. * then nothing is added.
  314. *
  315. * @return
  316. * An object populated with fields from the newly added database. If the
  317. * database already exists it returns the values in the current entry.
  318. *
  319. * @ingroup tripal_chado_api
  320. */
  321. function tripal_insert_db($values, $options = array()) {
  322. // Default Values
  323. $dbname = $values['name'];
  324. $description = (isset($values['description'])) ? $values['description'] : '';
  325. $url = (isset($values['url'])) ? $values['url'] : '';
  326. $urlprefix = (isset($values['urlprefix'])) ? $values['urlprefix'] : '';
  327. $update = (isset($options['update_existing'])) ? $options['update_existing'] : TRUE;
  328. // build the values array for inserting/updating
  329. $ins_values = array(
  330. 'name' => $dbname,
  331. 'description' => $description,
  332. 'url' => $url,
  333. 'urlprefix' => $urlprefix
  334. );
  335. // get the database record if it already exists
  336. $sel_values = array('name' => $dbname);
  337. $result = chado_select_record('db', array('*'), $sel_values);
  338. // if it does not exists then add it
  339. if (count($result) == 0) {
  340. $ins_options = array('statement_name' => 'ins_db_nadeurur');
  341. $success = chado_insert_record('db', $ins_values, $ins_options);
  342. if (!$success) {
  343. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Cannot create db '$dbname'.", NULL);
  344. return 0;
  345. }
  346. $result = chado_select_record('db', array('*'), $sel_values);
  347. }
  348. // if it exists and update is enabled the do the update
  349. elseif ($update) {
  350. $upd_options = array('statement_name' => 'upd_db_nadeurur');
  351. $success = chado_update_record('db', $sel_values, $ins_values, $upd_options);
  352. if (!$success) {
  353. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Cannot update db '$dbname'.", NULL);
  354. return 0;
  355. }
  356. $result = chado_select_record('db', array('*'), $sel_values);
  357. }
  358. // return the database object
  359. return $result[0];
  360. }
  361. /**
  362. * Add a database reference
  363. *
  364. * @param $values
  365. * An associative array of the values to be inserted including:
  366. * - db_id: the database_id of the database the reference is from
  367. * - accession: the accession
  368. * - version: (Optional) The version of the database reference
  369. * - description: (Optional) A description of the database reference
  370. *
  371. * @ingroup tripal_chado_api
  372. */
  373. function tripal_insert_dbxref($values) {
  374. $db_id = $values['db_id'];
  375. $accession = $values['accession'];
  376. $version = (isset($values['version'])) ? $values['version'] : '';
  377. $description = (isset($values['description'])) ? $values['description'] : '';
  378. $ins_values = array(
  379. 'db_id' => $db_id,
  380. 'accession' => $accession,
  381. 'version' => $version,
  382. 'description' => $description
  383. );
  384. // check to see if the dbxref exists
  385. $sel_values = array(
  386. 'db_id' => $db_id,
  387. 'accession' => $accession,
  388. 'version' => $version
  389. );
  390. $result = chado_select_record('dbxref', array('*'), $sel_values);
  391. // if it doesn't already exist then add it
  392. if (!$result) {
  393. $success = chado_insert_record('dbxref', $ins_values);
  394. if (!$success) {
  395. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to insert the dbxref record $accession", NULL);
  396. return 0;
  397. }
  398. $result = chado_select_record('dbxref', array('*'), $sel_values);
  399. }
  400. if (isset($result[0])) {
  401. return $result[0];
  402. }
  403. else {
  404. return FALSE;
  405. }
  406. }
  407. /**
  408. * Add a record to a database reference linking table (ie: feature_dbxref)
  409. *
  410. * @param $basetable
  411. * The base table for which the dbxref should be associated. Thus to associate a dbxref
  412. * with a feature the basetable=feature and dbxref_id is added to the feature_dbxref table
  413. * @param $record_id
  414. * The primary key of the basetable to associate the dbxref with. This should be in integer.
  415. * @param $dbxref
  416. * An associative array describing the dbxref. Valid keys include: 'accession' => the
  417. * accession for the dbxref, 'db_name' => the name of the database the dbxref belongs to;
  418. * 'db_id' => the primary key of the database the dbxref belongs to.
  419. * @param $options
  420. * An associative array of options. Valid keys include:
  421. * - insert_dbxref: Insert the dbxref if it doesn't already exist. TRUE is the default
  422. *
  423. * @ingroup tripal_chado_api
  424. */
  425. function tripal_associate_dbxref($basetable, $record_id, $dbxref, $options = array()) {
  426. $linking_table = $basetable . '_dbxref';
  427. $foreignkey_name = $basetable . '_id';
  428. // Default Values
  429. $options['insert_dbxref'] = (isset($options['insert_dbxref'])) ? $options['insert_dbxref'] : TRUE;
  430. // If the dbxref_id is set then we know it already exists
  431. // Otherwise, select to check
  432. if (!isset($dbxref['dbxref_id'])) {
  433. $values = array(
  434. 'accession' => $dbxref['accession'],
  435. );
  436. if (isset($dbxref['db_id'])) {
  437. $values['db_id'] = $dbxref['db_id'];
  438. } elseif (isset($dbxref['db_name'])) {
  439. $values['db_id'] = array(
  440. 'name' => $dbxref['db_name']
  441. );
  442. }
  443. else {
  444. tripal_report_error(
  445. 'tripal_chado_api',
  446. TRIPAL_WARNING,
  447. "tripal_associate_dbxref: The dbxref needs to have either the db_name or db_id
  448. supplied. You were trying to associate a dbxref with the %base %record_id
  449. and supplied the dbxref values: %dbxref.",
  450. array('%base' => $basetable, '%record_id' => $record_id, '%dbxref' => print_r($dbxref,TRUE))
  451. );
  452. return FALSE;
  453. }
  454. $select = chado_select_record('dbxref',array('*'), $values);
  455. if ($select) {
  456. $dbxref['dbxref_id'] = $select[0]->dbxref_id;
  457. }
  458. elseif ($options['insert_dbxref']) {
  459. // Insert the dbxref
  460. $insert = tripal_insert_dbxref($values);
  461. if (isset($insert->dbxref_id)) {
  462. $dbxref['dbxref_id'] = $insert->dbxref_id;
  463. }
  464. else {
  465. tripal_report_error(
  466. 'tripal_chado_api',
  467. TRIPAL_WARNING,
  468. "tripal_associate_dbxref: Unable to insert the dbxref using the dbxref values: %dbxref.",
  469. array('%dbxref' => print_r($dbxref,TRUE))
  470. );
  471. return FALSE;
  472. }
  473. }
  474. else {
  475. tripal_report_error(
  476. 'tripal_api',
  477. TRIPAL_WARNING,
  478. "tripal_associate_dbxref: The dbxref doesn't already exist. You supplied the dbxref values: %dbxref.",
  479. array('%dbxref' => print_r($dbxref,TRUE))
  480. );
  481. return FALSE;
  482. }
  483. }
  484. // Now add the link between the record & dbxref
  485. if ($dbxref['dbxref_id'] > 0) {
  486. $values = array(
  487. 'dbxref_id' => $dbxref['dbxref_id'],
  488. $foreignkey_name => $record_id
  489. );
  490. $result = chado_select_record($linking_table, array('*'), $values);
  491. // if it doesn't already exist then add it
  492. if (!$result) {
  493. $success = chado_insert_record($linking_table, $values);
  494. if (!$success) {
  495. tripal_report_error(
  496. 'tripal_api',
  497. TRIPAL_WARNING,
  498. "Failed to insert the %base record %accession",
  499. array('%base' => $linking_table, '%accession' => $dbxref['accession'])
  500. );
  501. return FALSE;
  502. }
  503. $result = chado_select_record($linking_table, array('*'), $values);
  504. }
  505. if (isset($result[0])) {
  506. return $result[0];
  507. }
  508. else {
  509. return FALSE;
  510. }
  511. }
  512. return FALSE;
  513. }
  514. /**
  515. * This function is intended to be used in autocomplete forms
  516. * for searching for accession that begin with the provided string
  517. *
  518. * @param $db_id
  519. * The DB ID in which to search for the term
  520. * @param $string
  521. * The string to search for
  522. *
  523. * @return
  524. * A json array of terms that begin with the provided string
  525. *
  526. * @ingroup tripal_db_api
  527. */
  528. function tripal_autocomplete_dbxref($db_id, $string = '') {
  529. if (!$db_id) {
  530. return drupal_json_output(array());
  531. }
  532. $sql = "
  533. SELECT dbxref_id, accession
  534. FROM {dbxref}
  535. WHERE db_id = :db_id and lower(accession) like lower(:accession)
  536. ORDER by accession
  537. LIMIT 25 OFFSET 0
  538. ";
  539. $results = chado_query($sql, array(':db_id' => $db_id, ':accession' => $string . '%'));
  540. $items = array();
  541. foreach ($results as $ref) {
  542. $items[$ref->accession] = $ref->accession;
  543. }
  544. drupal_json_output($items);
  545. }