tripal_core.chado_query.api.inc 55 KB

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