tripal_core.chado_query.api.inc 53 KB

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