tripal_core.chado_query.api.inc 53 KB

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