tripal_core.chado_query.api.inc 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715
  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. return FALSE;
  324. }
  325. elseif (sizeof($results) < 1) {
  326. tripal_report_error('tripal_core', TRIPAL_DEBUG,
  327. 'chado_insert_record: no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)',
  328. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
  329. array('print' => $print_errors)
  330. );
  331. return FALSE;
  332. }
  333. else {
  334. $insert_values[$field] = $results[0];
  335. }
  336. }
  337. else {
  338. $insert_values[$field] = $value;
  339. }
  340. }
  341. if ($validate) {
  342. // check for violation of any unique constraints
  343. $ukeys = array();
  344. if (array_key_exists('unique keys', $table_desc)) {
  345. $ukeys = $table_desc['unique keys'];
  346. }
  347. $ukselect_cols = array();
  348. $ukselect_vals = array();
  349. if ($ukeys) {
  350. foreach ($ukeys as $name => $fields) {
  351. foreach ($fields as $index => $field) {
  352. // build the arrays for performing a select that will check the contraint
  353. $ukselect_cols[] = $field;
  354. if (!array_key_exists($field, $insert_values)) {
  355. if (array_key_exists('default', $table_desc['fields'][$field])) {
  356. $ukselect_vals[$field] = $table_desc['fields'][$field]['default'];
  357. }
  358. }
  359. else {
  360. $ukselect_vals[$field] = $insert_values[$field];
  361. }
  362. }
  363. // now check the constraint
  364. if (chado_select_record($table, $ukselect_cols, $ukselect_vals)) {
  365. tripal_report_error('tripal_core', TRIPAL_ERROR,
  366. "chado_insert_record; Cannot insert duplicate record into $table table: !values",
  367. array('!values' => print_r($values, TRUE)), array('print' => $print_errors)
  368. );
  369. return FALSE;
  370. }
  371. }
  372. }
  373. // if trying to insert a field that is the primary key, make sure it also is unique
  374. if (array_key_exists('primary key', $table_desc)) {
  375. $pkey = $table_desc['primary key'][0];
  376. if (array_key_exists($pkey, $insert_values)) {
  377. $coptions = array();
  378. if (chado_select_record($table, array($pkey), array($pkey => $insert_values[$pkey]), $coptions)) {
  379. tripal_report_error('tripal_core', TRIPAL_ERROR,
  380. 'chado_insert_record; Cannot insert duplicate primary key into !table table: !values',
  381. array('!table' => $table, '!values' => print_r($values, TRUE)),
  382. array('print' => $print_errors)
  383. );
  384. return FALSE;
  385. }
  386. }
  387. }
  388. // make sure required fields have a value
  389. if (!is_array($table_desc['fields'])) {
  390. $table_desc['fields'] = array();
  391. tripal_report_error('tripal_core', TRIPAL_WARNING,
  392. "chado_insert_record; %table missing fields: \n %schema",
  393. array('%table' => $table, '%schema' => print_r($table_desc, 1)),
  394. array('print' => $print_errors)
  395. );
  396. }
  397. foreach ($table_desc['fields'] as $field => $def) {
  398. // a field is considered missing if it cannot be NULL and there is no default
  399. // value for it or it is of type 'serial'
  400. if (array_key_exists('NOT NULL', $def) and
  401. !array_key_exists($field, $insert_values) and
  402. !array_key_exists('default', $def) and
  403. strcmp($def['type'], serial) != 0) {
  404. tripal_report_error('tripal_core', TRIPAL_ERROR,
  405. "chado_insert_record; Field %table.%field cannot be NULL: %values",
  406. array('%table' => $table, '%field' => $field, '%values' => print_r($values, 1)),
  407. array('print' => $print_errors)
  408. );
  409. return FALSE;
  410. }
  411. }
  412. } //end of validation
  413. // Now build the insert SQL statement
  414. $ifields = array(); // contains the names of the fields
  415. $itypes = array(); // contains placeholders for the sql query
  416. $ivalues = array(); // contains the values of the fields
  417. $i = 1;
  418. foreach ($insert_values as $field => $value) {
  419. $ifields[] = $field;
  420. $ivalues[":$field"] = $value;
  421. $i++;
  422. if (strcmp($value, '__NULL__')==0) {
  423. $itypes[] = "NULL";
  424. }
  425. else {
  426. $itypes[] = ":$field";
  427. }
  428. }
  429. // create the SQL
  430. $sql = 'INSERT INTO {' . $table . '} (' . implode(", ", $ifields) . ") VALUES (" . implode(", ", $itypes) . ")";
  431. $result = chado_query($sql, $ivalues);
  432. // if we have a result then add primary keys to return array
  433. if ($options['return_record'] == TRUE and $result) {
  434. if (array_key_exists('primary key', $table_desc) and is_array($table_desc['primary key'])) {
  435. foreach ($table_desc['primary key'] as $field) {
  436. $sql = "SELECT CURRVAL('{" . $table . "_" . $field . "_seq}')";
  437. $results = chado_query($sql);
  438. $value = $results->fetchField();
  439. if (!$value) {
  440. tripal_report_error('tripal_core', TRIPAL_ERROR,
  441. "chado_insert_record; not able to retrieve primary key after insert: %sql",
  442. array('%sql' => $sql),
  443. array('print' => $print_errors)
  444. );
  445. return FALSE;
  446. }
  447. $values[$field] = $value;
  448. }
  449. }
  450. return $values;
  451. }
  452. elseif ($options['return_record'] == FALSE and $result) {
  453. return TRUE;
  454. }
  455. else {
  456. tripal_report_error('tripal_core', TRIPAL_ERROR,
  457. 'chado_insert_record; Cannot insert record into "%table": %values',
  458. array('%table' => $table, '%values' => print_r($values, 1)),
  459. array('print' => $print_errors)
  460. );
  461. return FALSE;
  462. }
  463. return FALSE;
  464. }
  465. /**
  466. * Provides a generic routine for updating into any Chado table
  467. *
  468. * Use this function to update a record in any Chado table. The first
  469. * argument specifies the table for inserting, the second is an array
  470. * of values to matched for locating the record for updating, and the third
  471. * argument give the values to update. The arrays are mutli-dimensional such
  472. * that foreign key lookup values can be specified.
  473. *
  474. * @param $table
  475. * The name of the chado table for inserting
  476. * @param $match
  477. * An associative array containing the values for locating a record to update.
  478. * @param $values
  479. * An associative array containing the values for updating.
  480. * @param $options
  481. * An array of options such as:
  482. * - return_record: by default, the function will return the TRUE if the record
  483. * was succesfully updated. However, set this option to TRUE to return the
  484. * record that was updated. The returned record will have the fields provided
  485. * but the primary key (if available for the table) will be added to the record.
  486. * @return
  487. * On success this function returns TRUE. On failure, it returns FALSE.
  488. *
  489. * Example usage:
  490. * @code
  491. $umatch = array(
  492. 'organism_id' => array(
  493. 'genus' => 'Citrus',
  494. 'species' => 'sinensis',
  495. ),
  496. 'uniquename' => 'orange1.1g000034m.g7',
  497. 'type_id' => array (
  498. 'cv_id' => array (
  499. 'name' => 'sequence',
  500. ),
  501. 'name' => 'gene',
  502. 'is_obsolete' => 0
  503. ),
  504. );
  505. $uvalues = array(
  506. 'name' => 'orange1.1g000034m.g',
  507. 'type_id' => array (
  508. 'cv_id' => array (
  509. 'name' => 'sequence',
  510. ),
  511. 'name' => 'mRNA',
  512. 'is_obsolete' => 0
  513. ),
  514. );
  515. * $result = chado_update_record('feature',$umatch,$uvalues);
  516. * @endcode
  517. * The above code species that a feature with a given uniquename, organism_id,
  518. * and type_id (the unique constraint for the feature table) will be updated.
  519. * The organism_id is specified as a nested array that uses the organism_id
  520. * foreign key constraint to lookup the specified values to find the exact
  521. * organism_id. The same nested struture is also used for specifying the
  522. * values to update. The function will find the record that matches the
  523. * columns specified and update the record with the avlues in the $uvalues array.
  524. *
  525. * @TODO: Support Complex filtering as is done in chado_select_record();
  526. *
  527. * @ingroup tripal_chado_query_api
  528. */
  529. function chado_update_record($table, $match, $values, $options = NULL) {
  530. $print_errors = (isset($options['print_errors'])) ? $options['print_errors'] : FALSE;
  531. if (!is_array($values)) {
  532. tripal_report_error('tripal_core', TRIPAL_ERROR,
  533. 'Cannot pass non array as values for updating.',
  534. array(), array('print' => $print_errors)
  535. );
  536. return FALSE;
  537. }
  538. if (count($values)==0) {
  539. tripal_report_error('tripal_core', TRIPAL_ERROR,
  540. 'Cannot pass an empty array as values for updating.',
  541. array(), array('print' => $print_errors)
  542. );
  543. return FALSE;
  544. }
  545. if (!is_array($match)) {
  546. tripal_report_error('tripal_core', TRIPAL_ERROR,
  547. 'Cannot pass non array as values for matching.',
  548. array(), array('print' => $print_errors)
  549. );
  550. return FALSE;
  551. }
  552. if (count($match)==0) {
  553. tripal_report_error('tripal_core', TRIPAL_ERROR,
  554. 'Cannot pass an empty array as values for matching.',
  555. array(), array('print' => $print_errors)
  556. );
  557. return FALSE;
  558. }
  559. // set defaults for options. If we don't set defaults then
  560. // we get memory leaks when we try to access the elements
  561. if (!is_array($options)) {
  562. $options = array();
  563. }
  564. if (!array_key_exists('return_record', $options)) {
  565. $options['return_record'] = FALSE;
  566. }
  567. $update_values = array(); // contains the values to be updated
  568. $update_matches = array(); // contains the values for the where clause
  569. // get the table description
  570. $table_desc = chado_get_schema($table);
  571. if (!$table_desc) {
  572. tripal_report_error('tripal_core', TRIPAL_ERROR,
  573. 'The table name, %table, does not exist.',
  574. array('%table', $table), array('print' => $print_errors)
  575. );
  576. return FALSE;
  577. }
  578. // if the user wants us to return the record then we need to get the
  579. // unique primary key if one exists. That way we can add it to the
  580. // values that get returned at the end of the function
  581. $pkeys = array();
  582. if ($options['return_record'] == TRUE) {
  583. if (array_key_exists('primary key', $table_desc) and is_array($table_desc['primary key'])) {
  584. $columns = array();
  585. $stmt_suffix = '';
  586. foreach ($table_desc['primary key'] as $field) {
  587. $columns[] = $field;
  588. $stmt_suffix .= substr($field, 0, 2);
  589. }
  590. $options2 = array();
  591. $results = chado_select_record($table, $columns, $match, $options2);
  592. if (count($results) > 0) {
  593. foreach ($results as $index => $pkey) {
  594. $pkeys[] = $pkey;
  595. }
  596. }
  597. }
  598. }
  599. // get the values needed for matching in the SQL statement
  600. foreach ($match as $field => $value) {
  601. if (is_array($value)) {
  602. $results = chado_schema_get_foreign_key($table_desc, $field, $value);
  603. if (sizeof($results) > 1) {
  604. tripal_report_error('tripal_core', TRIPAL_ERROR,
  605. 'chado_update_record: When trying to find record to update, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)',
  606. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
  607. array('print' => $print_errors)
  608. );
  609. return FALSE;
  610. }
  611. elseif (sizeof($results) < 1) {
  612. tripal_report_error('tripal_core', TRIPAL_DEBUG,
  613. 'chado_update_record: When trying to find record to update, no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)',
  614. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
  615. array('print' => $print_errors)
  616. );
  617. return FALSE;
  618. }
  619. else {
  620. $update_matches[$field] = $results[0];
  621. }
  622. }
  623. else {
  624. $update_matches[$field] = $value;
  625. }
  626. }
  627. // get the values used for updating
  628. foreach ($values as $field => &$value) {
  629. if (is_array($value)) {
  630. $foreign_options = array();
  631. // select the value from the foreign key relationship for this value
  632. $results = chado_schema_get_foreign_key($table_desc, $field, $value, $foreign_options);
  633. if (sizeof($results) > 1) {
  634. tripal_report_error('tripal_core', TRIPAL_ERROR,
  635. 'chado_update_record: When trying to find update values, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)',
  636. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
  637. array('print' => $print_errors)
  638. );
  639. return FALSE;
  640. }
  641. elseif (sizeof($results) < 1) {
  642. tripal_report_error('tripal_core', TRIPAL_DEBUG,
  643. 'chado_update_record: When trying to find update values, no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)',
  644. array('!foreign_key' => $field, '!criteria' => print_r($value,TRUE)),
  645. array('print' => $print_errors)
  646. );
  647. return FALSE;
  648. }
  649. else {
  650. $update_values[$field] = $results[0];
  651. }
  652. }
  653. else {
  654. $update_values[$field] = $value;
  655. }
  656. }
  657. // now build the SQL statement
  658. $sql = 'UPDATE {' . $table . '} SET ';
  659. $args = array(); // arguments passed to chado_query
  660. foreach ($update_values as $field => $value) {
  661. if (strcmp($value, '__NULL__') == 0) {
  662. $sql .= " $field = NULL, ";
  663. }
  664. else {
  665. $sql .= " $field = :$field, ";
  666. $args[":$field"] = $value;
  667. }
  668. }
  669. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing comma & space
  670. $sql .= " WHERE ";
  671. foreach ($update_matches as $field => $value) {
  672. if (strcmp($value, '__NULL__')==0) {
  673. $sql .= " $field = NULL AND ";
  674. }
  675. else {
  676. $sql .= " $field = :$field AND ";
  677. $args[":$field"] = $value;
  678. }
  679. }
  680. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND'
  681. $result = chado_query($sql, $args);
  682. // if we have a result then add primary keys to return array
  683. if ($options['return_record'] == TRUE and $result) {
  684. // only if we have a single result do we want to add the primary keys to the values
  685. // array. If the update matched many records we can't add the pkeys
  686. if (count($pkeys) == 1) {
  687. foreach ($pkeys as $index => $pkey) {
  688. foreach ($pkey as $field => $fvalue) {
  689. $values[$field] = $fvalue;
  690. }
  691. }
  692. }
  693. return $values;
  694. }
  695. elseif ($options['return_record'] == FALSE and $result) {
  696. return TRUE;
  697. }
  698. else {
  699. tripal_report_error('tripal_core', TRIPAL_ERROR,
  700. "chado_update_record: Cannot update record in %table table. \nMatch: %match \nValues: %values",
  701. array('%table' => table, '%match' => print_r($match,TRUE), '%values' => print_r($values, 1)),
  702. array('print' => $print_errors)
  703. );
  704. return FALSE;
  705. }
  706. return FALSE;
  707. }
  708. /**
  709. * Provides a generic function for deleting a record(s) from any chado table
  710. *
  711. * Use this function to delete a record(s) in any Chado table. The first
  712. * argument specifies the table to delete from and the second is an array
  713. * of values to match for locating the record(s) to be deleted. The arrays
  714. * are mutli-dimensional such that foreign key lookup values can be specified.
  715. *
  716. * @param $table
  717. * The name of the chado table for inserting
  718. * @param $match
  719. * An associative array containing the values for locating a record to update.
  720. * @param $options
  721. * Currently there are no options
  722. * @return
  723. * On success this function returns TRUE. On failure, it returns FALSE.
  724. *
  725. * Example usage:
  726. * @code
  727. $umatch = array(
  728. 'organism_id' => array(
  729. 'genus' => 'Citrus',
  730. 'species' => 'sinensis',
  731. ),
  732. 'uniquename' => 'orange1.1g000034m.g7',
  733. 'type_id' => array (
  734. 'cv_id' => array (
  735. 'name' => 'sequence',
  736. ),
  737. 'name' => 'gene',
  738. 'is_obsolete' => 0
  739. ),
  740. );
  741. $uvalues = array(
  742. 'name' => 'orange1.1g000034m.g',
  743. 'type_id' => array (
  744. 'cv_id' => array (
  745. 'name' => 'sequence',
  746. ),
  747. 'name' => 'mRNA',
  748. 'is_obsolete' => 0
  749. ),
  750. );
  751. * $result = chado_update_record('feature', $umatch, $uvalues);
  752. * @endcode
  753. * The above code species that a feature with a given uniquename, organism_id,
  754. * and type_id (the unique constraint for the feature table) will be deleted.
  755. * The organism_id is specified as a nested array that uses the organism_id
  756. * foreign key constraint to lookup the specified values to find the exact
  757. * organism_id. The same nested struture is also used for specifying the
  758. * values to update. The function will find all records that match the
  759. * columns specified and delete them.
  760. *
  761. * @TODO: Support Complex filtering as is done in chado_select_record();
  762. *
  763. * @ingroup tripal_chado_query_api
  764. */
  765. function chado_delete_record($table, $match, $options = NULL) {
  766. if (!is_array($match)) {
  767. tripal_report_error('tripal_core', TRIPAL_ERROR,
  768. 'Cannot pass non array as values for matching.', array());
  769. return FALSE;
  770. }
  771. if (count($match)==0) {
  772. tripal_report_error('tripal_core', TRIPAL_ERROR,
  773. 'Cannot pass an empty array as values for matching.', array());
  774. return FALSE;
  775. }
  776. // set defaults for options. If we don't set defaults then
  777. // we get memory leaks when we try to access the elements
  778. if (!is_array($options)) {
  779. $options = array();
  780. }
  781. $delete_matches = array(); // contains the values for the where clause
  782. // get the table description
  783. $table_desc = chado_get_schema($table);
  784. $fields = $table_desc['fields'];
  785. if (empty($table_desc)) {
  786. tripal_report_error('tripal_core', TRIPAL_WARNING,
  787. 'chado_insert_record; There is no table description for !table_name',
  788. array('!table_name' => $table), array('print' => $print_errors)
  789. );
  790. }
  791. // get the values needed for matching in the SQL statement
  792. foreach ($match as $field => $value) {
  793. if (is_array($value)) {
  794. // if the user has specified an array of values to delete rather than
  795. // FK relationships the keep those in our match
  796. if (array_values($value) === $value) {
  797. $delete_matches[$field] = $value;
  798. }
  799. else {
  800. $results = chado_schema_get_foreign_key($table_desc, $field, $value);
  801. if (sizeof($results) > 1) {
  802. tripal_report_error('tripal_core', TRIPAL_ERROR,
  803. 'chado_delete_record: When trying to find record to delete, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)',
  804. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)));
  805. return FALSE;
  806. }
  807. elseif (sizeof($results) < 1) {
  808. //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)));
  809. }
  810. else {
  811. $delete_matches[$field] = $results[0];
  812. }
  813. }
  814. }
  815. else {
  816. $delete_matches[$field] = $value;
  817. }
  818. }
  819. // now build the SQL statement
  820. $sql = 'DELETE FROM {' . $table . '} WHERE ';
  821. $args = array();
  822. foreach ($delete_matches as $field => $value) {
  823. // if we have an array values then this is an "IN" clasue.
  824. if (count($value) > 1) {
  825. $sql .= "$field IN (";
  826. $index = 0;
  827. foreach ($value as $v) {
  828. $sql .= ":$field" . $index . ", ";
  829. $args[":$field" . $index] = $v;
  830. $index++;
  831. }
  832. $sql = drupal_substr($sql, 0, -2); // get rid of trailing ', '
  833. $sql .= ") AND ";
  834. }
  835. else {
  836. if (strcmp($value, '__NULL__') == 0) {
  837. $sql .= " $field = NULL AND ";
  838. }
  839. else {
  840. $sql .= " $field = :$field AND ";
  841. $args[":$field"] = $value;
  842. }
  843. }
  844. }
  845. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND'
  846. // finally perform the delete. If successful, return the updated record
  847. $result = chado_query($sql, $args);
  848. if ($result) {
  849. return TRUE;
  850. }
  851. else {
  852. tripal_report_error('tripal_core', TRIPAL_ERROR,
  853. "Cannot delete record in $table table. Match:" . print_r($match, 1) . ". Values: " . print_r($values, 1), array());
  854. return FALSE;
  855. }
  856. return FALSE;
  857. }
  858. /**
  859. * Provides a generic routine for selecting data from a Chado table
  860. *
  861. * Use this function to perform a simple select from any Chado table.
  862. *
  863. * @param $table
  864. * The name of the chado table for inserting
  865. * @param $columns
  866. * An array of column names
  867. * @param $values
  868. * An associative array containing the values for filtering the results. In the
  869. * case where multiple values for the same time are to be selected an additional
  870. * entry for the field should appear for each value. If you need to filter
  871. * results using more complex methods see the 'Complex Filtering' section below.
  872. * @param $options
  873. * An associative array of additional options where the key is the option
  874. * and the value is the value of that option.
  875. *
  876. * Additional Options Include:
  877. * - has_record
  878. * Set this argument to 'TRUE' to have this function return a numeric
  879. * value for the number of records rather than the array of records. this
  880. * can be useful in 'if' statements to check the presence of particula records.
  881. * - return_sql
  882. * Set this to 'TRUE' to have this function return an array where the first
  883. * element is the sql that would have been run and the second is an array of
  884. * arguments.
  885. * - case_insensitive_columns
  886. * An array of columns to do a case insensitive search on.
  887. * - regex_columns
  888. * An array of columns where the value passed in should be treated as a regular expression
  889. * - order_by
  890. * An associative array containing the column names of the table as keys
  891. * and the type of sort (i.e. ASC, DESC) as the values. The results in the
  892. * query will be sorted by the key values in the direction listed by the value
  893. * - is_duplicate: TRUE or FALSE. Checks the values submited to see if
  894. * they violate any of the unique constraints. If so, the record
  895. * is returned, if not, FALSE is returned.
  896. * - pager: Use this option if it is desired to return only a subset of results
  897. * so that they may be shown with in a Drupal-style pager. This should be
  898. * an array with two keys: 'limit' and 'element'. The value of 'limit'
  899. * should specify the number of records to return and 'element' is a
  900. * unique integer to differentiate between pagers when more than one
  901. * appear on a page. The 'element' should start with zero and increment by
  902. * one for each pager.
  903. * -limit: Specifies the number of records to return.
  904. * -offset: Indicates the number of records to skip before returning records.
  905. *
  906. * @return
  907. * An array of results, FALSE if the query was not executed
  908. * correctly, an empty array if no records were matched, or the number of records
  909. * in the dataset if $has_record is set.
  910. * If the option 'is_duplicate' is provided and the record is a duplicate it
  911. * will return the duplicated record. If the 'has_record' option is provided
  912. * a value of TRUE will be returned if a record exists and FALSE will bee
  913. * returned if there are not records.
  914. *
  915. * Example usage:
  916. * @code
  917. * $columns = array('feature_id', 'name');
  918. * $values = array(
  919. * 'organism_id' => array(
  920. * 'genus' => 'Citrus',
  921. * 'species' => array('sinensis', 'clementina'),
  922. * ),
  923. * 'uniquename' => 'orange1.1g000034m.g',
  924. * 'type_id' => array (
  925. * 'cv_id' => array (
  926. * 'name' => 'sequence',
  927. * ),
  928. * 'name' => 'gene',
  929. * 'is_obsolete' => 0
  930. * ),
  931. * );
  932. * $options = array(
  933. * 'order_by' => array(
  934. * 'name' => 'ASC'
  935. * ),
  936. * );
  937. * $result = chado_select_record('feature',$columns,$values,$options);
  938. * @endcode
  939. * The above code selects a record from the feature table using the three fields
  940. * that uniquely identify a feature. The $columns array simply lists the columns
  941. * to select. The $values array is nested such that the organism is identified by
  942. * way of the organism_id foreign key constraint by specifying the genus and
  943. * species. The cvterm is also specified using its foreign key and the cv_id
  944. * for the cvterm is nested as well. In the example above, two different species
  945. * are allowed to match
  946. *
  947. * Complex Filtering:
  948. * All of the documentation above supports filtering based on 'is equal to'
  949. * or 'is NULL'. If your criteria doesn't fall into one of these two categories
  950. * then you need to provide an array with additional details such as the operator
  951. * as well as the value. An example follows and will be discussed in detail.
  952. * @code
  953. $columns = array('feature_id', 'fmin', 'fmax');
  954. // Regular criteria specifying the parent feature to retrieve locations from.
  955. $values = array(
  956. 'srcfeature_id' => array(
  957. 'uniquename' => 'MtChr01'
  958. 'type_id' => array(
  959. 'name' => 'pseudomolecule'
  960. ),
  961. ),
  962. );
  963. // Complex filtering to specify the range to return locations from.
  964. $values['fmin'][] = array(
  965. 'op' => '>',
  966. 'data' => 15
  967. );
  968. $values['fmin'][] = array(
  969. 'op' => '<',
  970. 'data' => 100
  971. );
  972. $results = chado_select_record('featureloc', $columns, $values);
  973. * @endcode
  974. * The above code example will return all of the name, start and end of all
  975. * the features that start within MtChr1:15-100bp. Note that complex filtering
  976. * can be used in conjunction with basic filtering and that multiple criteria,
  977. * even for the same field can be entered.
  978. *
  979. * @ingroup tripal_chado_query_api
  980. */
  981. function chado_select_record($table, $columns, $values, $options = NULL) {
  982. // Set defaults for options. If we don't set defaults then
  983. // we get memory leaks when we try to access the elements.
  984. if (!is_array($options)) {
  985. $options = array();
  986. }
  987. if (!array_key_exists('case_insensitive_columns', $options)) {
  988. $options['case_insensitive_columns'] = array();
  989. }
  990. if (!array_key_exists('regex_columns', $options)) {
  991. $options['regex_columns'] = array();
  992. }
  993. if (!array_key_exists('order_by', $options)) {
  994. $options['order_by'] = array();
  995. }
  996. if (!array_key_exists('return_sql', $options)) {
  997. $options['return_sql'] = FALSE;
  998. }
  999. if (!array_key_exists('has_record', $options)) {
  1000. $options['has_record'] = FALSE;
  1001. }
  1002. if (!array_key_exists('is_duplicate', $options)) {
  1003. $options['is_duplicate'] = FALSE;
  1004. }
  1005. $pager = array();
  1006. if (array_key_exists('pager', $options)) {
  1007. $pager = $options['pager'];
  1008. }
  1009. $print_errors = FALSE;
  1010. if (isset($options['print_errors'])) {
  1011. $print_errors = $options['print_errors'];
  1012. }
  1013. // Check that our columns and values arguments are proper arrays.
  1014. if (!is_array($columns)) {
  1015. tripal_report_error('tripal_core', TRIPAL_ERROR,
  1016. 'chado_select_record; the $columns argument must be an array. Columns:%columns',
  1017. array('%columns' => print_r($columns, TRUE)),
  1018. array('print' => $print_errors)
  1019. );
  1020. return FALSE;
  1021. }
  1022. if (!is_array($values)) {
  1023. tripal_report_error('tripal_core', TRIPAL_ERROR,
  1024. 'chado_select_record; the $values argument must be an array. Values:%values',
  1025. array('%values' => print_r($values, TRUE)),
  1026. array('print' => $print_errors)
  1027. );
  1028. return FALSE;
  1029. }
  1030. // Get the table description.
  1031. $table_desc = chado_get_schema($table);
  1032. if (empty($table_desc)) {
  1033. tripal_report_error('tripal_core', TRIPAL_WARNING,
  1034. 'chado_insert_record; There is no table description for !table_name',
  1035. array('!table_name' => $table), array('print' => $print_errors)
  1036. );
  1037. }
  1038. $select = '';
  1039. $from = '';
  1040. $where = array();
  1041. $args = array();
  1042. // if the 'is_duplicate' option is turned on then we want to remove all but unique keys
  1043. if ($options['is_duplicate'] and array_key_exists('unique keys', $table_desc)) {
  1044. $ukeys = $table_desc['unique keys'];
  1045. $has_results = 0;
  1046. // iterate through the unique constraints and reset the values and columns
  1047. // arrays to only include these fields
  1048. foreach ($ukeys as $cname => $fields) {
  1049. if ($has_results) {
  1050. continue;
  1051. }
  1052. $new_values = array();
  1053. $new_columns = array();
  1054. $new_options = array();
  1055. $uq_sname = "uq_" . $table . "_";
  1056. $has_pkey = 0;
  1057. // include the primary key in the results returned
  1058. if (array_key_exists('primary key', $table_desc)) {
  1059. $has_pkey = 1;
  1060. $pkeys = $table_desc['primary key'];
  1061. foreach ($pkeys as $index => $key) {
  1062. array_push($new_columns, $key);
  1063. }
  1064. }
  1065. // recreate the $values and $columns arrays
  1066. foreach ($fields as $field) {
  1067. if (array_key_exists($field, $values)) {
  1068. $new_values[$field] = $values[$field];
  1069. $uq_sname .= substr($field, 0, 2);
  1070. // if there is no primary key then use the unique contraint fields
  1071. if (!$has_pkey) {
  1072. array_push($new_columns, $field);
  1073. }
  1074. }
  1075. // if the field doesn't exist in the values array then
  1076. // substitute any default values
  1077. elseif (array_key_exists('default', $table_desc['fields'][$field])) {
  1078. $new_values[$field] = $table_desc['fields'][$field]['default'];
  1079. $uq_sname .= substr($field, 0, 2);
  1080. if (!$has_pkey) {
  1081. array_push($new_columns, $field);
  1082. }
  1083. }
  1084. // if there is no value (default or otherwise) check if this field is
  1085. // allowed to be null
  1086. elseif (!$table_desc['fields'][$field]['not null']) {
  1087. $new_values[$field] = NULL;
  1088. $uq_sname .= "n" . substr($field, 0, 2);
  1089. if (!$has_pkey) {
  1090. array_push($new_columns, $field);
  1091. }
  1092. }
  1093. // if the array key doesn't exist in the values given by the caller
  1094. // and there is no default value then we cannot check if the record
  1095. // is a duplicate so return FALSE
  1096. else {
  1097. tripal_report_error('tripal_core', TRIPAL_ERROR,
  1098. 'chado_select_record: There is no value for %field thus we cannot ' .
  1099. 'check if this record for table, %table, is unique. %values',
  1100. array('%field' => $field, '%table' => $table, '%values' => print_r($values, TRUE)),
  1101. array('print' => $print_errors));
  1102. return FALSE;
  1103. }
  1104. }
  1105. $results = chado_select_record($table, $new_columns, $new_values, $new_options);
  1106. // if we have a duplicate record then return the results
  1107. if (count($results) > 0) {
  1108. $has_results = 1;
  1109. }
  1110. unset($new_columns);
  1111. unset($new_values);
  1112. unset($new_options);
  1113. }
  1114. if ($options['has_record'] and $has_results) {
  1115. return TRUE;
  1116. }
  1117. else {
  1118. return $results;
  1119. }
  1120. }
  1121. // Process the values array into where clauses and retrieve foreign keys. The
  1122. // $where array should always be an integer-indexed array with each value
  1123. // being an array with a 'field', 'op', and 'data' keys with all foreign keys
  1124. // followed.
  1125. foreach ($values as $field => $value) {
  1126. // Require the field be in the table description.
  1127. if (!array_key_exists($field, $table_desc['fields'])) {
  1128. tripal_report_error('tripal_core', TRIPAL_ERROR,
  1129. 'chado_select_record: The field "%field" does not exist for the table "%table". Cannot perform query. Values: %array',
  1130. array('%field' => $field, '%table' => $table, '%array' => print_r($values, 1)),
  1131. array('print' => $print_errors)
  1132. );
  1133. return array();
  1134. }
  1135. $select[] = $field;
  1136. // CASE 1: We have an array for a value.
  1137. if (is_array($value)) {
  1138. // CASE 1a: If there is only one element in the array, treat it the same
  1139. // as a non-array value.
  1140. if (count($value) == 1 AND is_int(key($value))) {
  1141. $value = array_pop($value);
  1142. $op = '=';
  1143. chado_select_record_check_value_type($op, $value, $table_desc['fields'][$field]['type']);
  1144. $where[] = array(
  1145. 'field' => $field,
  1146. 'op' => $op,
  1147. 'data' => $value
  1148. );
  1149. }
  1150. // CASE 1b: If there is a 'data' key in the array then we have the new
  1151. // complex filtering format with a single criteria.
  1152. elseif (isset($value['data']) AND isset($value['op'])) {
  1153. $value['field'] = $field;
  1154. $where[] = $value;
  1155. }
  1156. // CASE 1c: If we have an integer indexed array and the first element is
  1157. // not an array then we have a simple array of values to be used for an IN clause.
  1158. elseif (is_int(key($value)) AND !is_array(current($value))) {
  1159. $where[] = array(
  1160. 'field' => $field,
  1161. 'op' => 'IN',
  1162. 'data' => $value
  1163. );
  1164. }
  1165. // We have a multi-dimensional array: 2 cases...
  1166. else {
  1167. // CASE 1d: If there is a multi-dimensional array with each sub-array
  1168. // containing a data key then we have the new complex filtering format
  1169. // with multiple criteria.
  1170. if (isset($value[0]['data']) AND isset($value[0]['op'])) {
  1171. foreach ($value as $subvalue) {
  1172. $subvalue['field'] = $field;
  1173. $where[] = $subvalue;
  1174. }
  1175. }
  1176. // CASE 1e: We have a multi-dimensional array that doesn't fit any of the
  1177. // above cases then we have a foreign key definition to follow.
  1178. else {
  1179. // Select the value from the foreign key relationship for this value.
  1180. $foreign_options = array(
  1181. 'regex_columns' => $options['regex_columns'],
  1182. );
  1183. $results = chado_schema_get_foreign_key($table_desc, $field, $value, $foreign_options);
  1184. // Ensure that looking up the foreign key didn't fail in an error.
  1185. if ($results === FALSE OR $results === NULL) {
  1186. tripal_report_error('tripal_core', TRIPAL_ERROR,
  1187. 'chado_select_record: could not follow the foreign key definition
  1188. for %field where the definition supplied was %value',
  1189. array('%field' => $field, '%value' => print_r($value, TRUE))
  1190. );
  1191. return array();
  1192. }
  1193. // Ensure that there were results returned.
  1194. elseif (count($results)==0) {
  1195. tripal_report_error('tripal_core', TRIPAL_ERROR,
  1196. 'chado_select_record: the foreign key definition for \'%field\' '.
  1197. 'returned no results where the definition supplied was %value',
  1198. array('%field' => $field, '%value' => print_r($value, TRUE))
  1199. );
  1200. return array();
  1201. }
  1202. // If there was only a single resutlt then add it using an op of =.
  1203. elseif (count($results) == 1) {
  1204. $results = array_pop($results);
  1205. $op = '=';
  1206. chado_select_record_check_value_type($op, $results, $table_desc['fields'][$field]['type']);
  1207. $where[] = array(
  1208. 'field' => $field,
  1209. 'op' => $op,
  1210. 'data' => $results
  1211. );
  1212. }
  1213. // Otherwise multiple results were returned so we want to form an
  1214. // IN (x, y, z) expression.
  1215. else {
  1216. $where[] = array(
  1217. 'field' => $field,
  1218. 'op' => 'IN',
  1219. 'data' => $results
  1220. );
  1221. }
  1222. }
  1223. }
  1224. }
  1225. // CASE 2: We have a single value.
  1226. else {
  1227. $op = '=';
  1228. chado_select_record_check_value_type($op, $value, $table_desc['fields'][$field]['type']);
  1229. $where[] = array(
  1230. 'field' => $field,
  1231. 'op' => $op,
  1232. 'data' => $value
  1233. );
  1234. }
  1235. // Support Deprecated method for regex conditions.
  1236. $current_key = key($where);
  1237. if (in_array($field, $options['regex_columns'])) {
  1238. $where[$current_key]['op'] = '~*';
  1239. }
  1240. }
  1241. // Now build the SQL.
  1242. if (empty($where)) {
  1243. // Sometimes want to select everything.
  1244. $sql = "SELECT " . implode(', ', $columns) . " ";
  1245. $sql .= 'FROM {' . $table . '} ';
  1246. }
  1247. else {
  1248. $sql = "SELECT " . implode(', ', $columns) . " ";
  1249. $sql .= 'FROM {' . $table . '} ';
  1250. // If $values is empty then we want all results so no where clause.
  1251. if (!empty($values)) {
  1252. $sql .= "WHERE ";
  1253. }
  1254. foreach ($where as $clause_num => $value_def) {
  1255. switch ($value_def['op']) {
  1256. // Deal with 'field IN (x, y, z)' where clauses.
  1257. case 'IN':
  1258. $sql .= $value_def['field'] . " IN (";
  1259. $index = 0;
  1260. foreach ($value_def['data'] as $v) {
  1261. $placeholder = ':' . $value_def['field'] . $clause_num .'_' . $index;
  1262. $sql .= $placeholder . ', ';
  1263. $args[$placeholder] = $v;
  1264. $index++;
  1265. }
  1266. $sql = drupal_substr($sql, 0, -2); // remove trailing ', '
  1267. $sql .= ") AND ";
  1268. break;
  1269. // Deal with IS NULL.
  1270. case 'IS NULL':
  1271. $sql .= $value_def['field'] . ' IS NULL AND ';
  1272. break;
  1273. // Default is [field] [op] [data].
  1274. default:
  1275. $placeholder = ':'. $value_def['field'] . $clause_num;
  1276. // Support case insensitive columns.
  1277. if (in_array($value_def['field'], $options['case_insensitive_columns'])) {
  1278. $sql .= 'lower(' . $value_def['field'] .') '. $value_def['op'] .' lower('. $placeholder . ') AND ';
  1279. }
  1280. else {
  1281. $sql .= $value_def['field'] .' '. $value_def['op'] .' '. $placeholder . ' AND ';
  1282. }
  1283. $args[$placeholder] = $value_def['data'];
  1284. }
  1285. } // end foreach item in where clause.
  1286. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND '
  1287. } // end if (empty($where)){ } else {
  1288. // Add any ordering of the results to the SQL statement.
  1289. if (count($options['order_by']) > 0) {
  1290. $sql .= " ORDER BY ";
  1291. foreach ($options['order_by'] as $field => $dir) {
  1292. $sql .= "$field $dir, ";
  1293. }
  1294. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing ', '
  1295. }
  1296. // Limit the records returned
  1297. if (array_key_exists('limit', $options) and is_numeric($options['limit'])) {
  1298. $sql .= " LIMIT " . $options['limit'];
  1299. if (array_key_exists('offset', $options) and is_numeric($options['offset'])) {
  1300. $sql .= " OFFSET " . $options['offset'];
  1301. }
  1302. }
  1303. // if the caller has requested the SQL rather than the results then do so.
  1304. if ($options['return_sql'] == TRUE) {
  1305. return array('sql' => $sql, 'args' => $args);
  1306. }
  1307. if (array_key_exists('limit', $pager)) {
  1308. $total_records = 0;
  1309. $resource = chado_pager_query($sql, $args, $pager['limit'], $pager['element'], NULL, $total_records);
  1310. }
  1311. else {
  1312. $resource = chado_query($sql, $args);
  1313. }
  1314. // Format results into an array.
  1315. $results = array();
  1316. foreach ($resource as $r) {
  1317. $results[] = $r;
  1318. }
  1319. if ($options['has_record']) {
  1320. return count($results);
  1321. }
  1322. return $results;
  1323. }
  1324. /**
  1325. * Helper Function: check that the value is the correct type.
  1326. *
  1327. * This function is used by chado_select_record() when building the $where
  1328. * clause array to ensure that any single values are the correct type based
  1329. * on the table definition. Furthermore, it ensures that NULL's are caught
  1330. * changing the operator to 'IS NULL'.
  1331. * @code
  1332. $op = '=';
  1333. chado_select_record_check_value_type($op, $value, $table_desc['fields'][$field]['type']);
  1334. $where[] = array(
  1335. 'field' => $field,
  1336. 'op' => $op,
  1337. 'data' => $value
  1338. );
  1339. * @endcode
  1340. *
  1341. * @param $op
  1342. * The operator being used. This is mostly passed in to allow it to be changed
  1343. * if a NULL value is detected.
  1344. * @param $value
  1345. * The value to be checked and adjusted.
  1346. * @param $type
  1347. * The type from the table definition that's used to determine the type of
  1348. * value.
  1349. */
  1350. function chado_select_record_check_value_type(&$op, &$value, $type) {
  1351. if ($value === NULL) {
  1352. $op = 'IS NULL';
  1353. }
  1354. elseif ($type == 'int') {
  1355. $value = (int) $value;
  1356. }
  1357. }
  1358. /**
  1359. * Use this function instead of db_query() to avoid switching databases
  1360. * when making query to the chado database
  1361. *
  1362. * Will use a chado persistent connection if it already exists
  1363. *
  1364. * @param $sql
  1365. * The sql statement to execute
  1366. *
  1367. * @param $args
  1368. * The array of arguments, with the same structure as passed to
  1369. * the db_query() function of Drupal.
  1370. *
  1371. * @return
  1372. * DatabaseStatementInterface A prepared statement object, already executed.
  1373. *
  1374. * Example usage:
  1375. * @code
  1376. * $sql = "SELECT F.name, CVT.name as type_name, ORG.common_name
  1377. * FROM {feature} F
  1378. * LEFT JOIN {cvterm} CVT ON F.type_id = CVT.cvterm_id
  1379. * LEFT JOIN {organism} ORG ON F.organism_id = ORG.organism_id
  1380. * WHERE
  1381. * F.uniquename = :feature_uniquename";
  1382. * $args = array( ':feature_uniquename' => $form_state['values']['uniquename'] );
  1383. * $result = chado_query( $sql, $args );
  1384. * foreach ($result as $r) { [Do something with the records here] }
  1385. * @endcode
  1386. *
  1387. * @ingroup tripal_chado_query_api
  1388. */
  1389. function chado_query($sql, $args = array()) {
  1390. $is_local = $GLOBALS["chado_is_local"];
  1391. // Args should be an array
  1392. if (!is_array($args)) {
  1393. tripal_report_error('tripal_core', TRIPAL_ERROR,
  1394. 'chado_query; Need to pass an array to chado_query, "%value" passed instead. Query: %query',
  1395. array('%value' => $args, '%query' => $sql)
  1396. );
  1397. return FALSE;
  1398. }
  1399. // if Chado is local to the database then prefix the Chado table
  1400. // names with 'chado'.
  1401. if ($is_local) {
  1402. $sql = preg_replace('/\n/', '', $sql); // remove carriage returns
  1403. $sql = preg_replace('/\{(.*?)\}/', 'chado.$1', $sql);
  1404. // the featureloc table has some indexes that use function that call other functions
  1405. // and those calls do not reference a schema, therefore, any tables with featureloc
  1406. // must automaticaly have the chado schema set as active to find
  1407. if (preg_match('/chado.featureloc/i', $sql) or preg_match('/chado.feature/i', $sql)) {
  1408. $previous_db = chado_set_active('chado') ;
  1409. $results = db_query($sql, $args);
  1410. chado_set_active($previous_db);
  1411. }
  1412. // for all other tables we should have everything in scope so just run the query
  1413. else {
  1414. $results = db_query($sql, $args);
  1415. }
  1416. }
  1417. // if Chado is not local to the Drupal database then we have to
  1418. // switch to another database
  1419. else {
  1420. $previous_db = chado_set_active('chado') ;
  1421. $results = db_query($sql, $args);
  1422. chado_set_active($previous_db);
  1423. }
  1424. return $results;
  1425. }
  1426. /**
  1427. * Use this function instead of pager_query() when selecting a
  1428. * subset of records from a Chado table.
  1429. *
  1430. * @param $query
  1431. * The SQL statement to execute, this is followed by a variable number of args
  1432. * used as substitution values in the SQL statement.
  1433. * @param $args
  1434. * The array of arguments for the query. They keys are the placeholders
  1435. * @param $limit
  1436. * The number of query results to display per page.
  1437. * @param $element
  1438. * An numeric identifier used to distinguish between multiple pagers on one page.
  1439. * @param $count_query
  1440. * An SQL query used to count matching records.
  1441. *
  1442. * @returns
  1443. * A database query result resource or FALSE if the query was not
  1444. * executed correctly
  1445. *
  1446. * @ingroup tripal_chado_query_api
  1447. */
  1448. function chado_pager_query($query, $args, $limit, $element, $count_query = '') {
  1449. // get the page and offset for the pager
  1450. $page = isset($_GET['page']) ? $_GET['page'] : '0';
  1451. $offset = $limit * $page;
  1452. $q = $_GET['q'];
  1453. // Construct a count query if none was given.
  1454. if (!isset($count_query)) {
  1455. $count_query = preg_replace(array('/SELECT.*?FROM /As', '/ORDER BY .*/'),
  1456. array('SELECT COUNT(*) FROM ', ''), $query);
  1457. }
  1458. // We calculate the total of pages as ceil(items / limit).
  1459. $results = chado_query($count_query, $args);
  1460. if (!$results) {
  1461. tripal_report_error('tripal_core', TRIPAL_ERROR,
  1462. "chado_pager_query(): Query failed: %cq", array('%cq' => $count_query));
  1463. return;
  1464. }
  1465. $total_records = $results->fetchField();
  1466. // set a session variable for storing the total number of records
  1467. $GLOBALS['chado_pager'][$q][$element]['total_records'] = $total_records;
  1468. pager_default_initialize($total_records, $limit, $element);
  1469. $query .= ' LIMIT ' . (int) $limit . ' OFFSET ' . (int) $offset;
  1470. $results = chado_query($query, $args);
  1471. return $results;
  1472. }
  1473. /**
  1474. * A function to retrieve the total number of records for a pager that
  1475. * was generated using the chado_pager_query() function
  1476. *
  1477. * @param $element
  1478. * The $element argument that was passed to the chado_pager_query function
  1479. *
  1480. * @ingroup tripal_chado_query_api
  1481. */
  1482. function chado_pager_get_count($element) {
  1483. $q = $_GET['q'];
  1484. if (array_key_exists($q, $GLOBALS['chado_pager']) and
  1485. array_key_exists($element, $GLOBALS['chado_pager'][$q])) {
  1486. return $GLOBALS['chado_pager'][$q][$element]['total_records'];
  1487. }
  1488. else {
  1489. return 0;
  1490. }
  1491. }
  1492. /**
  1493. * Gets the value of a foreign key relationship
  1494. *
  1495. * This function is used by chado_select_record, chado_insert_record,
  1496. * and chado_update_record to iterate through the associate array of
  1497. * values that gets passed to each of those routines. The values array
  1498. * is nested where foreign key contraints are used to specify a value that. See
  1499. * documentation for any of those functions for further information.
  1500. *
  1501. * @param $table_desc
  1502. * A table description for the table with the foreign key relationship to be identified generated by
  1503. * hook_chado_<table name>_schema()
  1504. * @param $field
  1505. * The field in the table that is the foreign key.
  1506. * @param $values
  1507. * An associative array containing the values
  1508. * @param $options
  1509. * An associative array of additional options where the key is the option
  1510. * and the value is the value of that option. These options are passed on to chado_select_record.
  1511. *
  1512. * Additional Options Include:
  1513. * - case_insensitive_columns
  1514. * An array of columns to do a case insensitive search on.
  1515. * - regex_columns
  1516. * An array of columns where the value passed in should be treated as a regular expression
  1517. *
  1518. * @return
  1519. * A string containg the results of the foreign key lookup, or FALSE if failed.
  1520. *
  1521. * Example usage:
  1522. * @code
  1523. *
  1524. * $values = array(
  1525. * 'genus' => 'Citrus',
  1526. * 'species' => 'sinensis',
  1527. * );
  1528. * $value = chado_schema_get_foreign_key('feature', 'organism_id',$values);
  1529. *
  1530. * @endcode
  1531. * The above code selects a record from the feature table using the three fields
  1532. * that uniquely identify a feature. The $columns array simply lists the columns
  1533. * to select. The $values array is nested such that the organism is identified by
  1534. * way of the organism_id foreign key constraint by specifying the genus and
  1535. * species. The cvterm is also specified using its foreign key and the cv_id
  1536. * for the cvterm is nested as well.
  1537. *
  1538. * @ingroup tripal_core
  1539. */
  1540. function chado_schema_get_foreign_key($table_desc, $field, $values, $options = NULL) {
  1541. // set defaults for options. If we don't set defaults then
  1542. // we get memory leaks when we try to access the elements
  1543. if (!is_array($options)) {
  1544. $options = array();
  1545. }
  1546. if (!array_key_exists('case_insensitive_columns', $options)) {
  1547. $options['case_insensitive_columns'] = array();
  1548. }
  1549. if (!array_key_exists('regex_columns', $options)) {
  1550. $options['regex_columns'] = array();
  1551. }
  1552. // get the list of foreign keys for this table description and
  1553. // iterate through those until we find the one we're looking for
  1554. $fkeys = '';
  1555. if (array_key_exists('foreign keys', $table_desc)) {
  1556. $fkeys = $table_desc['foreign keys'];
  1557. }
  1558. if ($fkeys) {
  1559. foreach ($fkeys as $name => $def) {
  1560. if (is_array($def['table'])) {
  1561. //foreign key was described 2X
  1562. $message = "The foreign key " . $name . " was defined twice. Please check modules "
  1563. . "to determine if hook_chado_schema_<version>_" . $table_desc['table'] . "() was "
  1564. . "implemented and defined this foreign key when it wasn't supposed to. Modules "
  1565. . "this hook was implemented in: " . implode(', ',
  1566. module_implements("chado_" . $table_desc['table'] . "_schema")) . ".";
  1567. tripal_report_error('tripal_core', $message);
  1568. drupal_set_message(check_plain($message), 'error');
  1569. continue;
  1570. }
  1571. $table = $def['table'];
  1572. $columns = $def['columns'];
  1573. // iterate through the columns of the foreign key relationship
  1574. foreach ($columns as $left => $right) {
  1575. // does the left column in the relationship match our field?
  1576. if (strcmp($field, $left) == 0) {
  1577. // the column name of the foreign key matches the field we want
  1578. // so this is the right relationship. Now we want to select
  1579. $select_cols = array($right);
  1580. $result = chado_select_record($table, $select_cols, $values, $options);
  1581. $fields = array();
  1582. if ($result and count($result) > 0) {
  1583. foreach ($result as $obj) {
  1584. $fields[] = $obj->$right;
  1585. }
  1586. return $fields;
  1587. }
  1588. }
  1589. }
  1590. }
  1591. }
  1592. else {
  1593. // @todo: what do we do if we get to this point and we have a fk
  1594. // relationship expected but we don't have any definition for one in the
  1595. // table schema??
  1596. $version = $GLOBALS["chado_version"];
  1597. $message = t("There is no foreign key relationship defined for " . $field . " .
  1598. To define a foreign key relationship, determine the table this foreign
  1599. key referrs to (<foreign table>) and then implement
  1600. hook_chado_chado_schema_v<version>_<foreign table>(). See
  1601. tripal_feature_chado_v1_2_schema_feature for an example. Chado version: $version");
  1602. tripal_report_error('tripal_core', $message);
  1603. drupal_set_message(check_plain($message), 'error');
  1604. }
  1605. return array();
  1606. }