tripal_core.chado_query.api.inc 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470
  1. <?php
  2. /**
  3. * @defgroup tripal_chado_query_api Chado Query API
  4. * @ingroup tripal_chado_api
  5. * @{
  6. * Provides an API for querying of chado including inserting, updating, deleting and
  7. * selecting from specific chado tables. There is also a generic function, chado_query(),
  8. * to execute and SQL statement on chado. It is ideal to use these functions to interact
  9. * with chado in order to keep your module compatible with both local & external chado
  10. * databases. Furthermore, it ensures connection to the chado database is taken care
  11. * of for you.
  12. *
  13. * Generic Queries to a specifc chado table:
  14. *
  15. * chado_select_record( [table name], [columns to select], [specify record to select], [options*] )
  16. * This function allows you to select various columns from the specified chado table. Although
  17. * you can only select from a single table, you can specify the record to select using values
  18. * from related tables through use of a nested array. For example, the following code shows
  19. * you how to select the name and uniquename of a feature based on it's type and source
  20. * organism.
  21. * @code
  22. * $values = array(
  23. * 'organism_id' => array(
  24. * 'genus' => 'Citrus',
  25. * 'species' => 'sinensis',
  26. * ),
  27. * 'type_id' => array (
  28. * 'cv_id' => array (
  29. * 'name' => 'sequence',
  30. * ),
  31. * 'name' => 'gene',
  32. * 'is_obsolete' => 0
  33. * ),
  34. * );
  35. * $result = chado_select_record(
  36. * 'feature', // table to select from
  37. * array('name', 'uniquename'), // columns to select
  38. * $values // record to select (see variable defn. above)
  39. * );
  40. * @endcode
  41. *
  42. * chado_insert_record( [table name], [values to insert], [options*] )
  43. * This function allows you to insert a single record into a specific table. The values to
  44. * insert are specified using an associative array where the keys are the column names to
  45. * insert into and they point to the value to be inserted into that column. If the column
  46. * is a foreign key, the key will point to an array specifying the record in the foreign
  47. * table and then the primary key of that record will be inserted in the column. For example,
  48. * the following code will insert a feature and for the type_id, the cvterm.cvterm_id of
  49. * the cvterm record will be inserted and for the organism_id, the organism.organism_id
  50. * of the organism_record will be inserted.
  51. * @code
  52. * $values = array(
  53. * 'organism_id' => array(
  54. * 'genus' => 'Citrus',
  55. * 'species' => 'sinensis',
  56. * ),
  57. * 'name' => 'orange1.1g000034m.g',
  58. * 'uniquename' => 'orange1.1g000034m.g',
  59. * 'type_id' => array (
  60. * 'cv_id' => array (
  61. * 'name' => 'sequence',
  62. * ),
  63. * 'name' => 'gene',
  64. * 'is_obsolete' => 0
  65. * ),
  66. * );
  67. * $result = chado_insert_record(
  68. * 'feature', // table to insert into
  69. * $values // values to insert
  70. * );
  71. * @endcode
  72. *
  73. * chado_update_record( [table name], [specify record to update], [values to change], [options*] )
  74. * This function allows you to update records in a specific chado table. The record(s)
  75. * you wish to update are specified the same as in the select function above and
  76. * the values to be update are specified the same as the values to be inserted were. For
  77. * example, the following code species that a feature with a given uniquename, organism_id,
  78. * and type_id (the unique constraint for the feature table) will be updated with a new name,
  79. * and the type changed from a gene to an mRNA.
  80. * @code
  81. * $umatch = array(
  82. * 'organism_id' => array(
  83. * 'genus' => 'Citrus',
  84. * 'species' => 'sinensis',
  85. * ),
  86. * 'uniquename' => 'orange1.1g000034m.g7',
  87. * 'type_id' => array (
  88. * 'cv_id' => array (
  89. * 'name' => 'sequence',
  90. * ),
  91. * 'name' => 'gene',
  92. * 'is_obsolete' => 0
  93. * ),
  94. * );
  95. * $uvalues = array(
  96. * 'name' => 'orange1.1g000034m.g',
  97. * 'type_id' => array (
  98. * 'cv_id' => array (
  99. * 'name' => 'sequence',
  100. * ),
  101. * 'name' => 'mRNA',
  102. * 'is_obsolete' => 0
  103. * ),
  104. * );
  105. * $result = chado_update_record('feature',$umatch,$uvalues);
  106. * @endcode
  107. *
  108. * chado_delete_record( [table name], [specify records to delete], [options*] )
  109. * This function allows you to delete records from a specific chado table. The record(s)
  110. * to delete are specified the same as the record to select/update was above. For example,
  111. * the following code will delete all genes from the organism Citrus sinensis.
  112. * @code
  113. * $values = array(
  114. * 'organism_id' => array(
  115. * 'genus' => 'Citrus',
  116. * 'species' => 'sinensis',
  117. * ),
  118. * 'type_id' => array (
  119. * 'cv_id' => array (
  120. * 'name' => 'sequence',
  121. * ),
  122. * 'name' => 'gene',
  123. * 'is_obsolete' => 0
  124. * ),
  125. * );
  126. * $result = chado_select_record(
  127. * 'feature', // table to select from
  128. * $values // records to delete (see variable defn. above)
  129. * );
  130. * @endcode
  131. *
  132. * Generic Queries for any SQL:
  133. * Often it is necessary to select from more then one table in chado or to execute
  134. * other complex queries that cannot be handled efficiently by the above functions. It is
  135. * for this reason that the chado_query( [sql string], [arguments to sub-in to the sql] )
  136. * function was created. This function allows you to execute any SQL directly on the
  137. * chado database and should be used with care. If any user input will be used in the query
  138. * make sure to put a placeholder in your SQL string and then define the value in the
  139. * arguments array. This will make sure that the user input is santized and safe through
  140. * type-checking and escaping. The following code shows an example of how to use user input
  141. * resulting from a form and would be called withing the form submit function.
  142. * @code
  143. * $sql = "SELECT F.name, CVT.name as type_name, ORG.common_name
  144. * FROM feature F
  145. * LEFT JOIN cvterm CVT ON F.type_id = CVT.cvterm_id
  146. * LEFT JOIN organism ORG ON F.organism_id = ORG.organism_id
  147. * WHERE
  148. * F.uniquename = :feature_uniquename";
  149. * $args = array( ':feature_uniquename' => $form_state['values']['uniquename'] );
  150. * $result = chado_query( $sql, $args );
  151. * foreach ($result as $r) { [Do something with the records here] }
  152. * @endcode
  153. *
  154. * If you are going to need more then a couple fields, you might want to use the
  155. * Chado Variables API (specifically chado_generate_var()) to select all
  156. * of the common fields needed including following foreign keys.
  157. */
  158. /**
  159. * Provides a generic routine for inserting into any Chado table
  160. *
  161. * Use this function to insert a record into any Chado table. The first
  162. * argument specifies the table for inserting and the second is an array
  163. * of values to be inserted. The array is mutli-dimensional such that
  164. * foreign key lookup values can be specified.
  165. *
  166. * @param $table
  167. * The name of the chado table for inserting
  168. * @param $values
  169. * An associative array containing the values for inserting.
  170. * @param $options
  171. * An array of options such as:
  172. * - skip_validation: TRUE or FALSE. If TRUE will skip all the validation steps and
  173. * just try to insert as is. This is much faster but results in unhandled
  174. * non user-friendly errors if the insert fails.
  175. * - return_record: by default, the function will return the record but with
  176. * the primary keys added after insertion. To simply return TRUE on success
  177. * set this option to FALSE
  178. *
  179. * @return
  180. * On success this function returns the inserted record with the new primary keys
  181. * added to the returned array. On failure, it returns FALSE.
  182. *
  183. * Example usage:
  184. * @code
  185. * $values = array(
  186. * 'organism_id' => array(
  187. * 'genus' => 'Citrus',
  188. * 'species' => 'sinensis',
  189. * ),
  190. * 'name' => 'orange1.1g000034m.g',
  191. * 'uniquename' => 'orange1.1g000034m.g',
  192. * 'type_id' => array (
  193. * 'cv_id' => array (
  194. * 'name' => 'sequence',
  195. * ),
  196. * 'name' => 'gene',
  197. * 'is_obsolete' => 0
  198. * ),
  199. * );
  200. * $result = chado_insert_record('feature',$values);
  201. * @endcode
  202. * The above code inserts a record into the feature table. The $values array is
  203. * nested such that the organism is selected by way of the organism_id foreign
  204. * key constraint by specifying the genus and species. The cvterm is also
  205. * specified using its foreign key and the cv_id for the cvterm is nested as
  206. * well.
  207. *
  208. * @ingroup tripal_chado_query_api
  209. */
  210. function chado_insert_record($table, $values, $options = array()) {
  211. $print_errors = (isset($options['print_errors'])) ? $options['print_errors'] : FALSE;
  212. if (!is_array($values)) {
  213. tripal_report_error('tripal_core', TRIPAL_ERROR,
  214. 'Cannot pass non array as values for inserting.', array(),
  215. array('print' => $print_errors)
  216. );
  217. return FALSE;
  218. }
  219. if (count($values)==0) {
  220. tripal_report_error('tripal_core', TRIPAL_ERROR,
  221. 'Cannot pass an empty array as values for inserting.',
  222. array(),array('print' => $print_errors)
  223. );
  224. return FALSE;
  225. }
  226. // set defaults for options. If we don't set defaults then
  227. // we get memory leaks when we try to access the elements
  228. if (!is_array($options)) {
  229. $options = array();
  230. }
  231. if (!array_key_exists('skip_validation', $options)) {
  232. $options['skip_validation'] = FALSE;
  233. }
  234. if (!array_key_exists('return_record', $options)) {
  235. $options['return_record'] = TRUE;
  236. }
  237. $insert_values = array();
  238. if (array_key_exists('skip_validation', $options)) {
  239. $validate = !$options['skip_validation'];
  240. }
  241. else {
  242. $validate = TRUE;
  243. }
  244. // get the table description
  245. $table_desc = chado_get_schema($table);
  246. if (empty($table_desc)) {
  247. tripal_report_error('tripal_core', TRIPAL_WARNING,
  248. 'chado_insert_record; There is no table description for !table_name',
  249. array('!table_name' => $table), array('print' => $print_errors)
  250. );
  251. }
  252. // iterate through the values array and create a new 'insert_values' array
  253. // that has all the values needed for insert with all foreign relationsihps
  254. // resolved.
  255. foreach ($values as $field => $value) {
  256. // make sure the field is in the table description. If not then return an error
  257. // message
  258. if (!array_key_exists($field, $table_desc['fields'])) {
  259. tripal_report_error('tripal_core', TRIPAL_ERROR,
  260. "chado_insert_record; The field '%field' does not exist " .
  261. "for the table '%table'. Cannot perform insert. Values: %array",
  262. array('%field' => $field, '%table' => $table, '%array' => print_r($values, 1)),
  263. array('print' => $print_errors)
  264. );
  265. return FALSE;
  266. }
  267. if (is_array($value)) {
  268. // select the value from the foreign key relationship for this value
  269. $results = chado_schema_get_foreign_key($table_desc, $field, $value);
  270. if (sizeof($results) > 1) {
  271. tripal_report_error('tripal_core', TRIPAL_ERROR,
  272. 'chado_insert_record: Too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)',
  273. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
  274. array('print' => $print_errors)
  275. );
  276. }
  277. elseif (sizeof($results) < 1) {
  278. tripal_report_error('tripal_core', TRIPAL_DEBUG,
  279. 'chado_insert_record: no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)',
  280. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
  281. array('print' => $print_errors)
  282. );
  283. }
  284. else {
  285. $insert_values[$field] = $results[0];
  286. }
  287. }
  288. else {
  289. $insert_values[$field] = $value;
  290. }
  291. }
  292. if ($validate) {
  293. // check for violation of any unique constraints
  294. $ukeys = array();
  295. if (array_key_exists('unique keys', $table_desc)) {
  296. $ukeys = $table_desc['unique keys'];
  297. }
  298. $ukselect_cols = array();
  299. $ukselect_vals = array();
  300. if ($ukeys) {
  301. foreach ($ukeys as $name => $fields) {
  302. foreach ($fields as $index => $field) {
  303. // build the arrays for performing a select that will check the contraint
  304. $ukselect_cols[] = $field;
  305. if (!array_key_exists($field, $insert_values)) {
  306. if (array_key_exists('default', $table_desc['fields'][$field])) {
  307. $ukselect_vals[$field] = $table_desc['fields'][$field]['default'];
  308. }
  309. }
  310. else {
  311. $ukselect_vals[$field] = $insert_values[$field];
  312. }
  313. }
  314. // now check the constraint
  315. if (chado_select_record($table, $ukselect_cols, $ukselect_vals)) {
  316. tripal_report_error('tripal_core', TRIPAL_ERROR,
  317. "chado_insert_record; Cannot insert duplicate record into $table table: !values",
  318. array('!values' => print_r($values, TRUE)), array('print' => $print_errors)
  319. );
  320. return FALSE;
  321. }
  322. }
  323. }
  324. // if trying to insert a field that is the primary key, make sure it also is unique
  325. if (array_key_exists('primary key', $table_desc)) {
  326. $pkey = $table_desc['primary key'][0];
  327. if (array_key_exists($pkey, $insert_values)) {
  328. $coptions = array();
  329. if (chado_select_record($table, array($pkey), array($pkey => $insert_values[$pkey]), $coptions)) {
  330. tripal_report_error('tripal_core', TRIPAL_ERROR,
  331. 'chado_insert_record; Cannot insert duplicate primary key into !table table: !values',
  332. array('!table' => $table, '!values' => print_r($values, TRUE)),
  333. array('print' => $print_errors)
  334. );
  335. return FALSE;
  336. }
  337. }
  338. }
  339. // make sure required fields have a value
  340. if (!is_array($table_desc['fields'])) {
  341. $table_desc['fields'] = array();
  342. tripal_report_error('tripal_core', TRIPAL_WARNING,
  343. "chado_insert_record; %table missing fields: \n %schema",
  344. array('%table' => $table, '%schema' => print_r($table_desc, 1)),
  345. array('print' => $print_errors)
  346. );
  347. }
  348. foreach ($table_desc['fields'] as $field => $def) {
  349. // a field is considered missing if it cannot be NULL and there is no default
  350. // value for it or it is of type 'serial'
  351. if (array_key_exists('NOT NULL', $def) and
  352. !array_key_exists($field, $insert_values) and
  353. !array_key_exists('default', $def) and
  354. strcmp($def['type'], serial) != 0) {
  355. tripal_report_error('tripal_core', TRIPAL_ERROR,
  356. "chado_insert_record; Field %table.%field cannot be NULL: %values",
  357. array('%table' => $table, '%field' => $field, '%values' => print_r($values, 1)),
  358. array('print' => $print_errors)
  359. );
  360. return FALSE;
  361. }
  362. }
  363. } //end of validation
  364. // Now build the insert SQL statement
  365. $ifields = array(); // contains the names of the fields
  366. $itypes = array(); // contains placeholders for the sql query
  367. $ivalues = array(); // contains the values of the fields
  368. $i = 1;
  369. foreach ($insert_values as $field => $value) {
  370. $ifields[] = $field;
  371. $ivalues[":$field"] = $value;
  372. $i++;
  373. if (strcmp($value, '__NULL__')==0) {
  374. $itypes[] = "NULL";
  375. }
  376. else {
  377. $itypes[] = ":$field";
  378. }
  379. }
  380. // create the SQL
  381. $sql = 'INSERT INTO {' . $table . '} (' . implode(", ", $ifields) . ") VALUES (" . implode(", ", $itypes) . ")";
  382. $result = chado_query($sql, $ivalues);
  383. // if we have a result then add primary keys to return array
  384. if ($options['return_record'] == TRUE and $result) {
  385. if (array_key_exists('primary key', $table_desc) and is_array($table_desc['primary key'])) {
  386. foreach ($table_desc['primary key'] as $field) {
  387. $sql = "SELECT CURRVAL('{" . $table . "_" . $field . "_seq}')";
  388. $results = chado_query($sql);
  389. $value = $results->fetchField();
  390. if (!$value) {
  391. tripal_report_error('tripal_core', TRIPAL_ERROR,
  392. "chado_insert_record; not able to retrieve primary key after insert: %sql",
  393. array('%sql' => $sql),
  394. array('print' => $print_errors)
  395. );
  396. return FALSE;
  397. }
  398. $values[$field] = $value;
  399. }
  400. }
  401. return $values;
  402. }
  403. elseif ($options['return_record'] == FALSE and $result) {
  404. return TRUE;
  405. }
  406. else {
  407. tripal_report_error('tripal_core', TRIPAL_ERROR,
  408. 'chado_insert_record; Cannot insert record into "%table": %values',
  409. array('%table' => $table, '%values' => print_r($values, 1)),
  410. array('print' => $print_errors)
  411. );
  412. return FALSE;
  413. }
  414. return FALSE;
  415. }
  416. /**
  417. * Provides a generic routine for updating into any Chado table
  418. *
  419. * Use this function to update a record in any Chado table. The first
  420. * argument specifies the table for inserting, the second is an array
  421. * of values to matched for locating the record for updating, and the third
  422. * argument give the values to update. The arrays are mutli-dimensional such
  423. * that foreign key lookup values can be specified.
  424. *
  425. * @param $table
  426. * The name of the chado table for inserting
  427. * @param $match
  428. * An associative array containing the values for locating a record to update.
  429. * @param $values
  430. * An associative array containing the values for updating.
  431. * @param $options
  432. * An array of options such as:
  433. * - return_record: by default, the function will return the TRUE if the record
  434. * was succesfully updated. However, set this option to TRUE to return the
  435. * record that was updated. The returned record will have the fields provided
  436. * but the primary key (if available for the table) will be added to the record.
  437. * @return
  438. * On success this function returns TRUE. On failure, it returns FALSE.
  439. *
  440. * Example usage:
  441. * @code
  442. $umatch = array(
  443. 'organism_id' => array(
  444. 'genus' => 'Citrus',
  445. 'species' => 'sinensis',
  446. ),
  447. 'uniquename' => 'orange1.1g000034m.g7',
  448. 'type_id' => array (
  449. 'cv_id' => array (
  450. 'name' => 'sequence',
  451. ),
  452. 'name' => 'gene',
  453. 'is_obsolete' => 0
  454. ),
  455. );
  456. $uvalues = array(
  457. 'name' => 'orange1.1g000034m.g',
  458. 'type_id' => array (
  459. 'cv_id' => array (
  460. 'name' => 'sequence',
  461. ),
  462. 'name' => 'mRNA',
  463. 'is_obsolete' => 0
  464. ),
  465. );
  466. * $result = chado_update_record('feature',$umatch,$uvalues);
  467. * @endcode
  468. * The above code species that a feature with a given uniquename, organism_id,
  469. * and type_id (the unique constraint for the feature table) will be updated.
  470. * The organism_id is specified as a nested array that uses the organism_id
  471. * foreign key constraint to lookup the specified values to find the exact
  472. * organism_id. The same nested struture is also used for specifying the
  473. * values to update. The function will find the record that matches the
  474. * columns specified and update the record with the avlues in the $uvalues array.
  475. *
  476. * @ingroup tripal_chado_query_api
  477. */
  478. function chado_update_record($table, $match, $values, $options = NULL) {
  479. $print_errors = (isset($options['print_errors'])) ? $options['print_errors'] : FALSE;
  480. if (!is_array($values)) {
  481. tripal_report_error('tripal_core', TRIPAL_ERROR,
  482. 'Cannot pass non array as values for updating.',
  483. array(), array('print' => $print_errors)
  484. );
  485. return FALSE;
  486. }
  487. if (count($values)==0) {
  488. tripal_report_error('tripal_core', TRIPAL_ERROR,
  489. 'Cannot pass an empty array as values for updating.',
  490. array(), array('print' => $print_errors)
  491. );
  492. return FALSE;
  493. }
  494. if (!is_array($match)) {
  495. tripal_report_error('tripal_core', TRIPAL_ERROR,
  496. 'Cannot pass non array as values for matching.',
  497. array(), array('print' => $print_errors)
  498. );
  499. return FALSE;
  500. }
  501. if (count($match)==0) {
  502. tripal_report_error('tripal_core', TRIPAL_ERROR,
  503. 'Cannot pass an empty array as values for matching.',
  504. array(), array('print' => $print_errors)
  505. );
  506. return FALSE;
  507. }
  508. // set defaults for options. If we don't set defaults then
  509. // we get memory leaks when we try to access the elements
  510. if (!is_array($options)) {
  511. $options = array();
  512. }
  513. if (!array_key_exists('return_record', $options)) {
  514. $options['return_record'] = FALSE;
  515. }
  516. $update_values = array(); // contains the values to be updated
  517. $update_matches = array(); // contains the values for the where clause
  518. // get the table description
  519. $table_desc = chado_get_schema($table);
  520. // if the user wants us to return the record then we need to get the
  521. // unique primary key if one exists. That way we can add it to the
  522. // values that get returned at the end of the function
  523. $pkeys = array();
  524. if ($options['return_record'] == TRUE) {
  525. if (array_key_exists('primary key', $table_desc) and is_array($table_desc['primary key'])) {
  526. $columns = array();
  527. $stmt_suffix = '';
  528. foreach ($table_desc['primary key'] as $field) {
  529. $columns[] = $field;
  530. $stmt_suffix .= substr($field, 0, 2);
  531. }
  532. $options2 = array();
  533. $results = chado_select_record($table, $columns, $match, $options2);
  534. if (count($results) > 0) {
  535. foreach ($results as $index => $pkey) {
  536. $pkeys[] = $pkey;
  537. }
  538. }
  539. }
  540. }
  541. // get the values needed for matching in the SQL statement
  542. foreach ($match as $field => $value) {
  543. if (is_array($value)) {
  544. $results = chado_schema_get_foreign_key($table_desc, $field, $value);
  545. if (sizeof($results) > 1) {
  546. tripal_report_error('tripal_core', TRIPAL_ERROR,
  547. 'chado_update_record: When trying to find record to update, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)',
  548. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
  549. array('print' => $print_errors)
  550. );
  551. }
  552. elseif (sizeof($results) < 1) {
  553. tripal_report_error('tripal_core', TRIPAL_DEBUG,
  554. 'chado_update_record: When trying to find record to update, no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)',
  555. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
  556. array('print' => $print_errors)
  557. );
  558. }
  559. else {
  560. $update_matches[$field] = $results[0];
  561. }
  562. }
  563. else {
  564. $update_matches[$field] = $value;
  565. }
  566. }
  567. // get the values used for updating
  568. foreach ($values as $field => $value) {
  569. if (is_array($value)) {
  570. $foreign_options = array();
  571. // select the value from the foreign key relationship for this value
  572. $results = chado_schema_get_foreign_key($table_desc, $field, $value, $foreign_options);
  573. if (sizeof($results) > 1) {
  574. tripal_report_error('tripal_core', TRIPAL_ERROR,
  575. 'chado_update_record: When trying to find update values, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)',
  576. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
  577. array('print' => $print_errors)
  578. );
  579. }
  580. elseif (sizeof($results) < 1) {
  581. tripal_report_error('tripal_core', TRIPAL_DEBUG,
  582. 'chado_update_record: When trying to find update values, no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)',
  583. array('!foreign_key' => $field, '!criteria' => print_r($value,TRUE)),
  584. array('print' => $print_errors)
  585. );
  586. }
  587. else {
  588. $update_values[$field] = $results[0];
  589. }
  590. }
  591. else {
  592. $update_values[$field] = $value;
  593. }
  594. }
  595. // now build the SQL statement
  596. $sql = 'UPDATE {' . $table . '} SET ';
  597. $args = array(); // arguments passed to chado_query
  598. foreach ($update_values as $field => $value) {
  599. if (strcmp($value, '__NULL__') == 0) {
  600. $sql .= " $field = NULL, ";
  601. }
  602. else {
  603. $sql .= " $field = :$field, ";
  604. $args[":$field"] = $value;
  605. }
  606. }
  607. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing comma & space
  608. $sql .= " WHERE ";
  609. foreach ($update_matches as $field => $value) {
  610. if (strcmp($value, '__NULL__')==0) {
  611. $sql .= " $field = NULL AND ";
  612. }
  613. else {
  614. $sql .= " $field = :$field AND ";
  615. $args[":$field"] = $value;
  616. }
  617. }
  618. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND'
  619. $result = chado_query($sql, $args);
  620. // if we have a result then add primary keys to return array
  621. if ($options['return_record'] == TRUE and $result) {
  622. // only if we have a single result do we want to add the primary keys to the values
  623. // array. If the update matched many records we can't add the pkeys
  624. if (count($pkeys) == 1) {
  625. foreach ($pkeys as $index => $pkey) {
  626. foreach ($pkey as $field => $fvalue) {
  627. $values[$field] = $fvalue;
  628. }
  629. }
  630. }
  631. return $values;
  632. }
  633. elseif ($options['return_record'] == FALSE and $result) {
  634. return TRUE;
  635. }
  636. else {
  637. tripal_report_error('tripal_core', TRIPAL_ERROR,
  638. "chado_update_record: Cannot update record in %table table. \nMatch: %match \nValues: %values",
  639. array('%table' => table, '%match' => print_r($match,TRUE), '%values' => print_r($values, 1)),
  640. array('print' => $print_errors)
  641. );
  642. return FALSE;
  643. }
  644. return FALSE;
  645. }
  646. /**
  647. * Provides a generic function for deleting a record(s) from any chado table
  648. *
  649. * Use this function to delete a record(s) in any Chado table. The first
  650. * argument specifies the table to delete from and the second is an array
  651. * of values to match for locating the record(s) to be deleted. The arrays
  652. * are mutli-dimensional such that foreign key lookup values can be specified.
  653. *
  654. * @param $table
  655. * The name of the chado table for inserting
  656. * @param $match
  657. * An associative array containing the values for locating a record to update.
  658. * @param $options
  659. * Currently there are no options
  660. * @return
  661. * On success this function returns TRUE. On failure, it returns FALSE.
  662. *
  663. * Example usage:
  664. * @code
  665. $umatch = array(
  666. 'organism_id' => array(
  667. 'genus' => 'Citrus',
  668. 'species' => 'sinensis',
  669. ),
  670. 'uniquename' => 'orange1.1g000034m.g7',
  671. 'type_id' => array (
  672. 'cv_id' => array (
  673. 'name' => 'sequence',
  674. ),
  675. 'name' => 'gene',
  676. 'is_obsolete' => 0
  677. ),
  678. );
  679. $uvalues = array(
  680. 'name' => 'orange1.1g000034m.g',
  681. 'type_id' => array (
  682. 'cv_id' => array (
  683. 'name' => 'sequence',
  684. ),
  685. 'name' => 'mRNA',
  686. 'is_obsolete' => 0
  687. ),
  688. );
  689. * $result = chado_update_record('feature', $umatch, $uvalues);
  690. * @endcode
  691. * The above code species that a feature with a given uniquename, organism_id,
  692. * and type_id (the unique constraint for the feature table) will be deleted.
  693. * The organism_id is specified as a nested array that uses the organism_id
  694. * foreign key constraint to lookup the specified values to find the exact
  695. * organism_id. The same nested struture is also used for specifying the
  696. * values to update. The function will find all records that match the
  697. * columns specified and delete them.
  698. *
  699. * @ingroup tripal_chado_query_api
  700. */
  701. function chado_delete_record($table, $match, $options = NULL) {
  702. if (!is_array($match)) {
  703. tripal_report_error('tripal_core', TRIPAL_ERROR,
  704. 'Cannot pass non array as values for matching.', array());
  705. return FALSE;
  706. }
  707. if (count($match)==0) {
  708. tripal_report_error('tripal_core', TRIPAL_ERROR,
  709. 'Cannot pass an empty array as values for matching.', array());
  710. return FALSE;
  711. }
  712. // set defaults for options. If we don't set defaults then
  713. // we get memory leaks when we try to access the elements
  714. if (!is_array($options)) {
  715. $options = array();
  716. }
  717. $delete_matches = array(); // contains the values for the where clause
  718. // get the table description
  719. $table_desc = chado_get_schema($table);
  720. $fields = $table_desc['fields'];
  721. // get the values needed for matching in the SQL statement
  722. foreach ($match as $field => $value) {
  723. if (is_array($value)) {
  724. // if the user has specified an array of values to delete rather than
  725. // FK relationships the keep those in our match
  726. if (array_values($value) === $value) {
  727. $delete_matches[$field] = $value;
  728. }
  729. else {
  730. $results = chado_schema_get_foreign_key($table_desc, $field, $value);
  731. if (sizeof($results) > 1) {
  732. tripal_report_error('tripal_core', TRIPAL_ERROR,
  733. 'chado_delete_record: When trying to find record to delete, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)',
  734. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)));
  735. }
  736. elseif (sizeof($results) < 1) {
  737. //tripal_report_error('tripal_core', TRIPAL_ERROR, 'chado_delete_record: 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)));
  738. }
  739. else {
  740. $delete_matches[$field] = $results[0];
  741. }
  742. }
  743. }
  744. else {
  745. $delete_matches[$field] = $value;
  746. }
  747. }
  748. // now build the SQL statement
  749. $sql = 'DELETE FROM {' . $table . '} WHERE ';
  750. $args = array();
  751. foreach ($delete_matches as $field => $value) {
  752. // if we have an array values then this is an "IN" clasue.
  753. // we cannot use prepared statements with these
  754. if (count($value) > 1) {
  755. $sql .= "$field IN (";
  756. $index = 0;
  757. foreach ($value as $v) {
  758. $sql .= ":$field" . $index . ", ";
  759. $args[":$field" . $index] = $v;
  760. $index++;
  761. }
  762. $sql = drupal_substr($sql, 0, -2); // get rid of trailing ', '
  763. $sql .= ") AND ";
  764. }
  765. else {
  766. if (strcmp($value, '__NULL__') == 0) {
  767. $sql .= " $field = NULL AND ";
  768. }
  769. else {
  770. $sql .= " $field = :$field AND ";
  771. $args[":$field"] = $value;
  772. }
  773. }
  774. }
  775. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND'
  776. // finally perform the delete. If successful, return the updated record
  777. $result = chado_query($sql, $args);
  778. if ($result) {
  779. return TRUE;
  780. }
  781. else {
  782. tripal_report_error('tripal_core', TRIPAL_ERROR,
  783. "Cannot delete record in $table table. Match:" . print_r($match, 1) . ". Values: " . print_r($values, 1), array());
  784. return FALSE;
  785. }
  786. return FALSE;
  787. }
  788. /**
  789. * Provides a generic routine for selecting data from a Chado table
  790. *
  791. * Use this function to perform a simple select from any Chado table.
  792. *
  793. * @param $table
  794. * The name of the chado table for inserting
  795. * @param $columns
  796. * An array of column names
  797. * @param $values
  798. * An associative array containing the values for filtering the results. In the
  799. * case where multiple values for the same time are to be selected an additional
  800. * entry for the field should appear for each value
  801. * @param $options
  802. * An associative array of additional options where the key is the option
  803. * and the value is the value of that option.
  804. *
  805. * Additional Options Include:
  806. * - has_record
  807. * Set this argument to 'TRUE' to have this function return a numeric
  808. * value for the number of recrods rather than the array of records. this
  809. * can be useful in 'if' statements to check the presence of particula records.
  810. * - return_sql
  811. * Set this to 'TRUE' to have this function return an array where the first
  812. * element is the sql that would have been run and the second is an array of
  813. * arguments.
  814. * - case_insensitive_columns
  815. * An array of columns to do a case insensitive search on.
  816. * - regex_columns
  817. * An array of columns where the value passed in should be treated as a regular expression
  818. * - order_by
  819. * An associative array containing the column names of the table as keys
  820. * and the type of sort (i.e. ASC, DESC) as the values. The results in the
  821. * query will be sorted by the key values in the direction listed by the value
  822. * - is_duplicate: TRUE or FALSE. Checks the values submited to see if
  823. * they violate any of the unique constraints. If so, the record
  824. * is returned, if not, FALSE is returned.
  825. * - pager: Use this option if it is desired to return only a subset of results
  826. * so that they may be shown with in a Drupal-style pager. This should be
  827. * an array with two keys: 'limit' and 'element'. The value of 'limit'
  828. * should specify the number of records to return and 'element' is a
  829. * unique integer to differentiate between pagers when more than one
  830. * appear on a page. The 'element' should start with zero and increment by
  831. * one for each pager.
  832. *
  833. * @return
  834. * An array of results, FALSE if the query was not executed
  835. * correctly, an empty array if no records were matched, or the number of records
  836. * in the dataset if $has_record is set.
  837. * If the option 'is_duplicate' is provided and the record is a duplicate it
  838. * will return the duplicated record. If the 'has_record' option is provided
  839. * a value of TRUE will be returned if a record exists and FALSE will bee
  840. * returned if there are not records.
  841. *
  842. * Example usage:
  843. * @code
  844. * $columns = array('feature_id', 'name');
  845. * $values = array(
  846. * 'organism_id' => array(
  847. * 'genus' => 'Citrus',
  848. * 'species' => array('sinensis', 'clementina'),
  849. * ),
  850. * 'uniquename' => 'orange1.1g000034m.g',
  851. * 'type_id' => array (
  852. * 'cv_id' => array (
  853. * 'name' => 'sequence',
  854. * ),
  855. * 'name' => 'gene',
  856. * 'is_obsolete' => 0
  857. * ),
  858. * );
  859. * $options = array(
  860. * 'order_by' => array(
  861. * 'name' => 'ASC'
  862. * ),
  863. * );
  864. * $result = chado_select_record('feature',$columns,$values,$options);
  865. * @endcode
  866. * The above code selects a record from the feature table using the three fields
  867. * that uniquely identify a feature. The $columns array simply lists the columns
  868. * to select. The $values array is nested such that the organism is identified by
  869. * way of the organism_id foreign key constraint by specifying the genus and
  870. * species. The cvterm is also specified using its foreign key and the cv_id
  871. * for the cvterm is nested as well. In the example above, two different species
  872. * are allowed to match
  873. *
  874. * @ingroup tripal_chado_query_api
  875. */
  876. function chado_select_record($table, $columns, $values, $options = NULL) {
  877. $print_errors = (isset($options['print_errors'])) ? $options['print_errors'] : FALSE;
  878. if (!is_array($values)) {
  879. tripal_report_error('tripal_core', TRIPAL_ERROR, 'Cannot pass non array as values for selecting.',
  880. array(), array('print' => $print_errors)
  881. );
  882. return FALSE;
  883. }
  884. if (!is_array($columns)) {
  885. tripal_report_error('tripal_core', TRIPAL_ERROR, 'Cannot pass non array as columns for selecting.',
  886. array(), array('print' => $print_errors)
  887. );
  888. return FALSE;
  889. }
  890. if (count($columns)==0) {
  891. tripal_report_error('tripal_core', TRIPAL_ERROR, 'Cannot pass an empty array as columns for selecting.',
  892. array(), array('print' => $print_errors)
  893. );
  894. return FALSE;
  895. }
  896. // set defaults for options. If we don't set defaults then
  897. // we get memory leaks when we try to access the elements
  898. if (!is_array($options)) {
  899. $options = array();
  900. }
  901. if (!array_key_exists('case_insensitive_columns', $options)) {
  902. $options['case_insensitive_columns'] = array();
  903. }
  904. if (!array_key_exists('regex_columns', $options)) {
  905. $options['regex_columns'] = array();
  906. }
  907. if (!array_key_exists('order_by', $options)) {
  908. $options['order_by'] = array();
  909. }
  910. if (!array_key_exists('return_sql', $options)) {
  911. $options['return_sql'] = FALSE;
  912. }
  913. if (!array_key_exists('has_record', $options)) {
  914. $options['has_record'] = FALSE;
  915. }
  916. if (!array_key_exists('is_duplicate', $options)) {
  917. $options['is_duplicate'] = FALSE;
  918. }
  919. $pager = array();
  920. if (array_key_exists('pager', $options)) {
  921. $pager = $options['pager'];
  922. }
  923. // check that our columns and values arguments are proper arrays
  924. if (!is_array($columns)) {
  925. tripal_report_error('tripal_core', TRIPAL_ERROR,
  926. 'chado_select_record; the $columns argument must be an array. Columns:%columns',
  927. array('%columns' => print_r($columns, TRUE)),
  928. array('print' => $print_errors)
  929. );
  930. return FALSE;
  931. }
  932. if (!is_array($values)) {
  933. tripal_report_error('tripal_core', TRIPAL_ERROR,
  934. 'chado_select_record; the $values argument must be an array. Values:%values',
  935. array('%values' => print_r($values, TRUE)),
  936. array('print' => $print_errors)
  937. );
  938. return FALSE;
  939. }
  940. // get the table description
  941. $table_desc = chado_get_schema($table);
  942. $select = '';
  943. $from = '';
  944. $where = array();
  945. $args = array();
  946. // if the 'use_unique' option is turned on then we want
  947. // to remove all but unique keys
  948. if ($options['is_duplicate'] and array_key_exists('unique keys', $table_desc)) {
  949. $ukeys = $table_desc['unique keys'];
  950. $has_results = 0;
  951. // iterate through the unique constraints and reset the values and columns
  952. // arrays to only include these fields
  953. foreach ($ukeys as $cname => $fields) {
  954. if ($has_results) {
  955. continue;
  956. }
  957. $new_values = array();
  958. $new_columns = array();
  959. $new_options = array();
  960. $uq_sname = "uq_" . $table . "_";
  961. $has_pkey = 0;
  962. // include the primary key in the results returned
  963. if (array_key_exists('primary key', $table_desc)) {
  964. $has_pkey = 1;
  965. $pkeys = $table_desc['primary key'];
  966. foreach ($pkeys as $index => $key) {
  967. array_push($new_columns, $key);
  968. }
  969. }
  970. // recreate the $values and $columns arrays
  971. foreach ($fields as $field) {
  972. if (array_key_exists($field, $values)) {
  973. $new_values[$field] = $values[$field];
  974. $uq_sname .= substr($field, 0, 2);
  975. // if there is no primary key then use the unique contraint fields
  976. if (!$has_pkey) {
  977. array_push($new_columns, $field);
  978. }
  979. }
  980. // if the field doesn't exist in the values array then
  981. // substitute any default values
  982. elseif (array_key_exists('default', $table_desc['fields'][$field])) {
  983. $new_values[$field] = $table_desc['fields'][$field]['default'];
  984. $uq_sname .= substr($field, 0, 2);
  985. if (!$has_pkey) {
  986. array_push($new_columns, $field);
  987. }
  988. }
  989. // if there is no value (default or otherwise) check if this field is
  990. // allowed to be null
  991. elseif (!$table_desc['fields'][$field]['not null']) {
  992. $new_values[$field] = NULL;
  993. $uq_sname .= "n" . substr($field, 0, 2);
  994. if (!$has_pkey) {
  995. array_push($new_columns, $field);
  996. }
  997. }
  998. // if the array key doesn't exist in the values given by the caller
  999. // and there is no default value then we cannot check if the record
  1000. // is a duplicate so return FALSE
  1001. else {
  1002. tripal_report_error('tripal_core', TRIPAL_ERROR,
  1003. 'chado_select_record: There is no value for %field thus we cannot check if this record is unique',
  1004. array('%field' => $field), array('print' => $print_errors));
  1005. return FALSE;
  1006. }
  1007. }
  1008. $results = chado_select_record($table, $new_columns, $new_values, $new_options);
  1009. // if we have a duplicate record then return the results
  1010. if (count($results) > 0) {
  1011. $has_results = 1;
  1012. }
  1013. unset($new_columns);
  1014. unset($new_values);
  1015. unset($new_options);
  1016. }
  1017. if ($options['has_record'] and $has_results) {
  1018. return TRUE;
  1019. }
  1020. else {
  1021. return $results;
  1022. }
  1023. }
  1024. foreach ($values as $field => $value) {
  1025. // make sure the field is in the table description. If not then return an error
  1026. // message
  1027. if (!array_key_exists($field, $table_desc['fields'])) {
  1028. tripal_report_error('tripal_core', TRIPAL_ERROR,
  1029. 'chado_select_record: The field "%field" does not exist for the table "%table". Cannot perform query. Values: %array',
  1030. array('%field' => $field, '%table' => $table, '%array' => print_r($values, 1)),
  1031. array('print' => $print_errors)
  1032. );
  1033. return array();
  1034. }
  1035. $select[] = $field;
  1036. if (is_array($value)) {
  1037. // if the user has specified multiple values for matching then this we
  1038. // want to catch that and save them in our $where array, otherwise
  1039. // we'll descend for a foreign key relationship
  1040. if (array_values($value) === $value) {
  1041. $where[$field] = $value;
  1042. }
  1043. else {
  1044. // select the value from the foreign key relationship for this value
  1045. $foreign_options = array(
  1046. 'regex_columns' => $options['regex_columns'],
  1047. );
  1048. $results = chado_schema_get_foreign_key($table_desc, $field, $value, $foreign_options);
  1049. if (!$results or count($results)==0) {
  1050. return array();
  1051. }
  1052. else {
  1053. $where[$field] = $results;
  1054. }
  1055. }
  1056. }
  1057. else {
  1058. // need to catch a 0 and make int if integer field
  1059. // but we don't want to catch a NULL
  1060. if ($value === NULL) {
  1061. $where[$field] = NULL;
  1062. }
  1063. elseif ($table_desc['fields'][$field]['type'] == 'int') {
  1064. $where[$field][] = (int) $value;
  1065. }
  1066. else {
  1067. $where[$field][] = $value;
  1068. }
  1069. }
  1070. }
  1071. // now build the SQL and prepared SQL statements. We may not use
  1072. // the prepared statement if it wasn't requested in the options or if the
  1073. // argument in a where statement has multiple values.
  1074. if (empty($where)) {
  1075. // sometimes want to select everything
  1076. $sql = "SELECT " . implode(', ', $columns) . " ";
  1077. $sql .= 'FROM {' . $table . '} ';
  1078. // we don't prepare a statement if there is no where clause
  1079. $prepared = FALSE;
  1080. }
  1081. else {
  1082. $sql = "SELECT " . implode(', ', $columns) . " ";
  1083. $sql .= 'FROM {' . $table . '} ';
  1084. // if $values is empty then we want all results so no where clause
  1085. if (!empty($values)) {
  1086. $sql .= "WHERE ";
  1087. }
  1088. foreach ($where as $field => $value) {
  1089. // if we have multiple values returned then we need an 'IN' statement
  1090. // in our where statement
  1091. if (count($value) > 1) {
  1092. $sql .= "$field IN (";
  1093. $index = 0;
  1094. foreach ($value as $v) {
  1095. $sql .= ":$field" . $index . ', ';
  1096. $args[":$field" . $index] = $v;
  1097. $index++;
  1098. }
  1099. $sql = drupal_substr($sql, 0, -2); // remove trailing ', '
  1100. $sql .= ") AND ";
  1101. }
  1102. // if we have a null value then we need an IS NULL in our where statement
  1103. elseif ($value === NULL) {
  1104. $sql .= "$field IS NULL AND ";
  1105. // Need to remove one from the argument count b/c nulls don't add an argument
  1106. }
  1107. // if we have a single value then we need an = in our where statement
  1108. else {
  1109. $operator = '=';
  1110. if (in_array($field, $options['regex_columns'])) {
  1111. $operator = '~*';
  1112. }
  1113. if (in_array($field, $options['case_insensitive_columns'])) {
  1114. $sql .= "lower($field) $operator lower(:$field) AND ";
  1115. $args[":$field"] = $value[0];
  1116. }
  1117. else {
  1118. $sql .= "$field $operator :$field AND ";
  1119. $args[":$field"] = $value[0];
  1120. }
  1121. }
  1122. } // end foreach item in where clause
  1123. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND '
  1124. } // end if (empty($where)){ } else {
  1125. // finally add any ordering of the results to the SQL statement
  1126. if (count($options['order_by']) > 0) {
  1127. $sql .= " ORDER BY ";
  1128. foreach ($options['order_by'] as $field => $dir) {
  1129. $sql .= "$field $dir, ";
  1130. }
  1131. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing ', '
  1132. }
  1133. // if the caller has requested the SQL rather than the results then do so
  1134. if ($options['return_sql'] == TRUE) {
  1135. return array('sql' => $sql, 'args' => $args);
  1136. }
  1137. if (array_key_exists('limit', $pager)) {
  1138. $total_records = 0;
  1139. $resource = chado_pager_query($sql, $args, $pager['limit'], $pager['element'], NULL, $total_records);
  1140. }
  1141. else {
  1142. $resource = chado_query($sql, $args);
  1143. }
  1144. // format results into an array
  1145. $results = array();
  1146. foreach ($resource as $r) {
  1147. $results[] = $r;
  1148. }
  1149. if ($options['has_record']) {
  1150. return count($results);
  1151. }
  1152. return $results;
  1153. }
  1154. /**
  1155. * Use this function instead of db_query() to avoid switching databases
  1156. * when making query to the chado database
  1157. *
  1158. * Will use a chado persistent connection if it already exists
  1159. *
  1160. * @param $sql
  1161. * The sql statement to execute
  1162. *
  1163. * @param $args
  1164. * The array of arguments, with the same structure as passed to
  1165. * the db_query() function of Drupal.
  1166. *
  1167. * @return
  1168. * DatabaseStatementInterface A prepared statement object, already executed.
  1169. *
  1170. * Example usage:
  1171. * @code
  1172. * $sql = "SELECT F.name, CVT.name as type_name, ORG.common_name
  1173. * FROM feature F
  1174. * LEFT JOIN cvterm CVT ON F.type_id = CVT.cvterm_id
  1175. * LEFT JOIN organism ORG ON F.organism_id = ORG.organism_id
  1176. * WHERE
  1177. * F.uniquename = :feature_uniquename";
  1178. * $args = array( ':feature_uniquename' => $form_state['values']['uniquename'] );
  1179. * $result = chado_query( $sql, $args );
  1180. * foreach ($result as $r) { [Do something with the records here] }
  1181. * @endcode
  1182. *
  1183. * @ingroup tripal_chado_query_api
  1184. */
  1185. function chado_query($sql, $args = array()) {
  1186. $is_local = $GLOBALS["chado_is_local"];
  1187. // Args should be an array
  1188. if (!is_array($args)) {
  1189. tripal_report_error('tripal_core', TRIPAL_ERROR,
  1190. 'chado_query; Need to pass an array to chado_query, "%value" passed instead. Query: %query',
  1191. array('%value' => $args, '%query' => $sql)
  1192. );
  1193. $args = array($args);
  1194. return FALSE;
  1195. }
  1196. // if Chado is local to the database then prefix the Chado table
  1197. // names with 'chado'.
  1198. if ($is_local) {
  1199. $sql = preg_replace('/\n/', '', $sql); // remove carriage returns
  1200. $sql = preg_replace('/\{(.*?)\}/', 'chado.$1', $sql);
  1201. // the featureloc table has some indexes that use function that call other functions
  1202. // and those calls do not reference a schema, therefore, any tables with featureloc
  1203. // must automaticaly have the chado schema set as active to find
  1204. if(preg_match('/chado.featureloc/i', $sql)) {
  1205. $previous_db = chado_set_active('chado') ;
  1206. $results = db_query($sql, $args);
  1207. chado_set_active($previous_db);
  1208. }
  1209. // for all other tables we should have everything in scope so just run the query
  1210. else {
  1211. $results = db_query($sql, $args);
  1212. }
  1213. }
  1214. // if Chado is not local to the Drupal database then we have to
  1215. // switch to another database
  1216. else {
  1217. $previous_db = chado_set_active('chado') ;
  1218. $results = db_query($sql, $args);
  1219. chado_set_active($previous_db);
  1220. }
  1221. return $results;
  1222. }
  1223. /**
  1224. * Use this function instead of pager_query() when selecting a
  1225. * subset of records from a Chado table.
  1226. *
  1227. * @param $query
  1228. * The SQL statement to execute, this is followed by a variable number of args
  1229. * used as substitution values in the SQL statement.
  1230. * @param $args
  1231. * The array of arguments for the query. They keys are the placeholders
  1232. * @param $limit
  1233. * The number of query results to display per page.
  1234. * @param $element
  1235. * An optional integer to distinguish between multiple pagers on one page.
  1236. * @param $count_query
  1237. * An SQL query used to count matching records.
  1238. *
  1239. * @returns
  1240. * A database query result resource or FALSE if the query was not
  1241. * executed correctly
  1242. *
  1243. * @ingroup tripal_chado_query_api
  1244. */
  1245. function chado_pager_query($query, $args, $limit, $element, $count_query = '') {
  1246. // get the page and offset for the pager
  1247. $page = isset($_GET['page']) ? $_GET['page'] : '0';
  1248. $offset = $limit * $page;
  1249. // Construct a count query if none was given.
  1250. if (!isset($count_query)) {
  1251. $count_query = preg_replace(array('/SELECT.*?FROM /As', '/ORDER BY .*/'),
  1252. array('SELECT COUNT(*) FROM ', ''), $query);
  1253. }
  1254. // We calculate the total of pages as ceil(items / limit).
  1255. $results = chado_query($count_query, $args);
  1256. if (!$results) {
  1257. tripal_report_error('tripal_core', TRIPAL_ERROR,
  1258. "chado_pager_query(): Query failed: %cq", array('%cq' => $count_query));
  1259. return;
  1260. }
  1261. $total_records = $results->fetchField();
  1262. // set a session variable for storing the total number of records
  1263. $_SESSION['chado_pager'][$element]['total_records'] = $total_records;
  1264. pager_default_initialize($total_records, $limit, $element);
  1265. $query .= ' LIMIT ' . (int) $limit . ' OFFSET ' . (int) $offset;
  1266. $results = chado_query($query, $args);
  1267. return $results;
  1268. }
  1269. /**
  1270. * Gets the value of a foreign key relationship
  1271. *
  1272. * This function is used by chado_select_record, chado_insert_record,
  1273. * and chado_update_record to iterate through the associate array of
  1274. * values that gets passed to each of those routines. The values array
  1275. * is nested where foreign key contraints are used to specify a value that. See
  1276. * documentation for any of those functions for further information.
  1277. *
  1278. * @param $table_desc
  1279. * A table description for the table with the foreign key relationship to be identified generated by
  1280. * hook_chado_<table name>_schema()
  1281. * @param $field
  1282. * The field in the table that is the foreign key.
  1283. * @param $values
  1284. * An associative array containing the values
  1285. * @param $options
  1286. * An associative array of additional options where the key is the option
  1287. * and the value is the value of that option. These options are passed on to chado_select_record.
  1288. *
  1289. * Additional Options Include:
  1290. * - case_insensitive_columns
  1291. * An array of columns to do a case insensitive search on.
  1292. * - regex_columns
  1293. * An array of columns where the value passed in should be treated as a regular expression
  1294. *
  1295. * @return
  1296. * A string containg the results of the foreign key lookup, or FALSE if failed.
  1297. *
  1298. * Example usage:
  1299. * @code
  1300. *
  1301. * $values = array(
  1302. * 'genus' => 'Citrus',
  1303. * 'species' => 'sinensis',
  1304. * );
  1305. * $value = chado_schema_get_foreign_key('feature', 'organism_id',$values);
  1306. *
  1307. * @endcode
  1308. * The above code selects a record from the feature table using the three fields
  1309. * that uniquely identify a feature. The $columns array simply lists the columns
  1310. * to select. The $values array is nested such that the organism is identified by
  1311. * way of the organism_id foreign key constraint by specifying the genus and
  1312. * species. The cvterm is also specified using its foreign key and the cv_id
  1313. * for the cvterm is nested as well.
  1314. *
  1315. * @ingroup tripal_core
  1316. */
  1317. function chado_schema_get_foreign_key($table_desc, $field, $values, $options = NULL) {
  1318. // set defaults for options. If we don't set defaults then
  1319. // we get memory leaks when we try to access the elements
  1320. if (!is_array($options)) {
  1321. $options = array();
  1322. }
  1323. if (!array_key_exists('case_insensitive_columns', $options)) {
  1324. $options['case_insensitive_columns'] = array();
  1325. }
  1326. if (!array_key_exists('regex_columns', $options)) {
  1327. $options['regex_columns'] = array();
  1328. }
  1329. // get the list of foreign keys for this table description and
  1330. // iterate through those until we find the one we're looking for
  1331. $fkeys = '';
  1332. if (array_key_exists('foreign keys', $table_desc)) {
  1333. $fkeys = $table_desc['foreign keys'];
  1334. }
  1335. if ($fkeys) {
  1336. foreach ($fkeys as $name => $def) {
  1337. if (is_array($def['table'])) {
  1338. //foreign key was described 2X
  1339. $message = "The foreign key " . $name . " was defined twice. Please check modules "
  1340. . "to determine if hook_chado_schema_<version>_" . $table_desc['table'] . "() was "
  1341. . "implemented and defined this foreign key when it wasn't supposed to. Modules "
  1342. . "this hook was implemented in: " . implode(', ',
  1343. module_implements("chado_" . $table_desc['table'] . "_schema")) . ".";
  1344. tripal_report_error('tripal_core', $message);
  1345. drupal_set_message(check_plain($message), 'error');
  1346. continue;
  1347. }
  1348. $table = $def['table'];
  1349. $columns = $def['columns'];
  1350. // iterate through the columns of the foreign key relationship
  1351. foreach ($columns as $left => $right) {
  1352. // does the left column in the relationship match our field?
  1353. if (strcmp($field, $left) == 0) {
  1354. // the column name of the foreign key matches the field we want
  1355. // so this is the right relationship. Now we want to select
  1356. $select_cols = array($right);
  1357. $result = chado_select_record($table, $select_cols, $values, $options);
  1358. $fields = array();
  1359. if ($result and count($result) > 0) {
  1360. foreach ($result as $obj) {
  1361. $fields[] = $obj->$right;
  1362. }
  1363. return $fields;
  1364. }
  1365. }
  1366. }
  1367. }
  1368. }
  1369. else {
  1370. // @todo: what do we do if we get to this point and we have a fk
  1371. // relationship expected but we don't have any definition for one in the
  1372. // table schema??
  1373. $version = $GLOBALS["chado_version"];
  1374. $message = t("There is no foreign key relationship defined for " . $field . " .
  1375. To define a foreign key relationship, determine the table this foreign
  1376. key referrs to (<foreign table>) and then implement
  1377. hook_chado_chado_schema_v<version>_<foreign table>(). See
  1378. tripal_feature_chado_v1_2_schema_feature for an example. Chado version: $version");
  1379. tripal_report_error('tripal_core', $message);
  1380. drupal_set_message(check_plain($message), 'error');
  1381. }
  1382. return array();
  1383. }