tripal_core.chado_query.api.inc 60 KB

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