tripal_core.chado_query.api.inc 54 KB

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