tripal_core.chado_query.api.inc 53 KB

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