tripal_chado.query.api.inc 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899
  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. * Get max rank for a given set of criteria
  9. * This function was developed with the many property tables in chado in mind but will
  10. * work for any table with a rank
  11. *
  12. * @params tablename: the name of the chado table you want to select the max rank from
  13. * this table must contain a rank column of type integer
  14. * @params where_options: array(
  15. * <column_name> => array(
  16. * 'type' => <type of column: INT/STRING>,
  17. * 'value' => <the value you want to filter on>,
  18. * 'exact' => <if TRUE use =; if FALSE use ~>,
  19. * )
  20. * )
  21. * where options should include the id and type for that table to correctly
  22. * group a set of records together where the only difference are the value and rank
  23. *
  24. * @return the maximum rank
  25. *
  26. * @ingroup tripal_chado_api
  27. */
  28. function chado_get_table_max_rank($tablename, $where_options) {
  29. $where_clauses = array();
  30. $where_args = array();
  31. //generate the where clause from supplied options
  32. // the key is the column name
  33. $i = 0;
  34. $sql = "
  35. SELECT max(rank) as max_rank, count(rank) as count
  36. FROM {".$tablename."}
  37. WHERE
  38. ";
  39. foreach ($where_options as $key => $value) {
  40. $where_clauses[] = "$key = :$key";
  41. $where_args[":$key"] = $value;
  42. }
  43. $sql .= implode($where_clauses, ' AND ');
  44. $result = chado_query($sql, $where_args)->fetchObject();
  45. if ($result->count > 0) {
  46. return $result->max_rank;
  47. }
  48. else {
  49. return -1;
  50. }
  51. }
  52. /**
  53. * Alter Chado connection settings.
  54. *
  55. * This hook is useful for multi-chado instances. Tripal core functions
  56. * call the chado_set_active() function (e.g. chado_query) but there is no
  57. * opportunity elsewhere to set the active database. This is useful in two
  58. * cases: 1) Users are managed at the database level as in the case of
  59. * SouthGreen Bioinformatics Platform tools (e.g. Banana Genone Hub).
  60. * This allows custom modules to change the database connections on a per-user
  61. * basis, and each user permissions is managed at the database level. Users
  62. * are managed at the database level to provid the same access restrictions
  63. * across various tools that use Chado (e,g, Artemis) 2) When there are
  64. * simply two Chado instances housed in different Chado databases and the
  65. * module needs to control which one is being used at any given time.
  66. *
  67. * @param $settings
  68. * An array containing
  69. *
  70. * @see chado_set_active()
  71. *
  72. * @ingroup tripal_chado_api
  73. */
  74. function hook_chado_connection_alter(&$settings) {
  75. // This example shows how we could make sure no table of the 'public' schema
  76. // would be allowed in the coming queries: to do so, the caller will call
  77. // "chado_set_active('chado_only');" and the hook will remove 'public' from
  78. // the search path.
  79. if ('chado_only' == $settings['dbname']) {
  80. $settings['new_active_db'] = 'chado';
  81. // We don't include 'public' in search path.
  82. $settings['new_search_path'] = 'chado';
  83. }
  84. }
  85. /**
  86. * Set the Tripal Database
  87. *
  88. * The chado_set_active function is used to prevent namespace collisions
  89. * when Chado and Drupal are installed in the same database but in different
  90. * schemas. It is also used when using Drupal functions such as
  91. * db_table_exists().
  92. *
  93. * The connection settings can be altered through the hook
  94. * hook_chado_connection_alter.
  95. *
  96. * Current active connection name is stored in the global variable
  97. * $GLOBALS['chado_active_db'].
  98. *
  99. * @see hook_chado_connection_alter()
  100. *
  101. * @ingroup tripal_chado_api
  102. */
  103. function chado_set_active($dbname = 'default') {
  104. // Check if the chado_active_db has been set yet.
  105. if (!array_key_exists('chado_active_db', $GLOBALS)) {
  106. $GLOBALS['chado_active_db'] = 'default';
  107. }
  108. $previous_db = $active_db = $GLOBALS['chado_active_db'];
  109. $search_path = 'public';
  110. // Change only if 'chado' has been specified.
  111. if ($dbname == 'chado') {
  112. $active_db = 'chado';
  113. $search_path = 'chado,public';
  114. }
  115. $settings = array(
  116. 'dbname' => $dbname,
  117. 'new_active_db' => &$active_db,
  118. 'new_search_path' => &$search_path,
  119. );
  120. // Will call all modules implementing hook_chado_search_path_alter
  121. // note: hooks can alter $active_db and $search_path.
  122. drupal_alter('chado_connection', $settings);
  123. // set chado_active_db to remember active db
  124. $GLOBALS['chado_active_db'] = $active_db;
  125. // set PostgreSQL search_path
  126. db_query('SET search_path TO ' . $search_path);
  127. return $previous_db;
  128. }
  129. /**
  130. * @defgroup tripal_chado_query_api Chado Query API
  131. * @ingroup tripal_chado_api
  132. * @{
  133. * Provides an API for querying of chado including inserting, updating, deleting and
  134. * selecting from specific chado tables. There is also a generic function, chado_query(),
  135. * to execute and SQL statement on chado. It is ideal to use these functions to interact
  136. * with chado in order to keep your module compatible with both local & external chado
  137. * databases. Furthermore, it ensures connection to the chado database is taken care
  138. * of for you.
  139. *
  140. * Generic Queries to a specifc chado table:
  141. *
  142. * chado_select_record( [table name], [columns to select], [specify record to select], [options*] )
  143. * This function allows you to select various columns from the specified chado table. Although
  144. * you can only select from a single table, you can specify the record to select using values
  145. * from related tables through use of a nested array. For example, the following code shows
  146. * you how to select the name and uniquename of a feature based on it's type and source
  147. * organism.
  148. * @code
  149. * $values = array(
  150. * 'organism_id' => array(
  151. * 'genus' => 'Citrus',
  152. * 'species' => 'sinensis',
  153. * ),
  154. * 'type_id' => array (
  155. * 'cv_id' => array (
  156. * 'name' => 'sequence',
  157. * ),
  158. * 'name' => 'gene',
  159. * 'is_obsolete' => 0
  160. * ),
  161. * );
  162. * $result = chado_select_record(
  163. * 'feature', // table to select from
  164. * array('name', 'uniquename'), // columns to select
  165. * $values // record to select (see variable defn. above)
  166. * );
  167. * @endcode
  168. *
  169. * chado_insert_record( [table name], [values to insert], [options*] )
  170. * This function allows you to insert a single record into a specific table. The values to
  171. * insert are specified using an associative array where the keys are the column names to
  172. * insert into and they point to the value to be inserted into that column. If the column
  173. * is a foreign key, the key will point to an array specifying the record in the foreign
  174. * table and then the primary key of that record will be inserted in the column. For example,
  175. * the following code will insert a feature and for the type_id, the cvterm.cvterm_id of
  176. * the cvterm record will be inserted and for the organism_id, the organism.organism_id
  177. * of the organism_record will be inserted.
  178. * @code
  179. * $values = array(
  180. * 'organism_id' => array(
  181. * 'genus' => 'Citrus',
  182. * 'species' => 'sinensis',
  183. * ),
  184. * 'name' => 'orange1.1g000034m.g',
  185. * 'uniquename' => 'orange1.1g000034m.g',
  186. * 'type_id' => array (
  187. * 'cv_id' => array (
  188. * 'name' => 'sequence',
  189. * ),
  190. * 'name' => 'gene',
  191. * 'is_obsolete' => 0
  192. * ),
  193. * );
  194. * $result = chado_insert_record(
  195. * 'feature', // table to insert into
  196. * $values // values to insert
  197. * );
  198. * @endcode
  199. *
  200. * chado_update_record( [table name], [specify record to update], [values to change], [options*] )
  201. * This function allows you to update records in a specific chado table. The record(s)
  202. * you wish to update are specified the same as in the select function above and
  203. * the values to be update are specified the same as the values to be inserted were. For
  204. * example, the following code species that a feature with a given uniquename, organism_id,
  205. * and type_id (the unique constraint for the feature table) will be updated with a new name,
  206. * and the type changed from a gene to an mRNA.
  207. * @code
  208. * $umatch = array(
  209. * 'organism_id' => array(
  210. * 'genus' => 'Citrus',
  211. * 'species' => 'sinensis',
  212. * ),
  213. * 'uniquename' => 'orange1.1g000034m.g7',
  214. * 'type_id' => array (
  215. * 'cv_id' => array (
  216. * 'name' => 'sequence',
  217. * ),
  218. * 'name' => 'gene',
  219. * 'is_obsolete' => 0
  220. * ),
  221. * );
  222. * $uvalues = array(
  223. * 'name' => 'orange1.1g000034m.g',
  224. * 'type_id' => array (
  225. * 'cv_id' => array (
  226. * 'name' => 'sequence',
  227. * ),
  228. * 'name' => 'mRNA',
  229. * 'is_obsolete' => 0
  230. * ),
  231. * );
  232. * $result = chado_update_record('feature',$umatch,$uvalues);
  233. * @endcode
  234. *
  235. * chado_delete_record( [table name], [specify records to delete], [options*] )
  236. * This function allows you to delete records from a specific chado table. The record(s)
  237. * to delete are specified the same as the record to select/update was above. For example,
  238. * the following code will delete all genes from the organism Citrus sinensis.
  239. * @code
  240. * $values = array(
  241. * 'organism_id' => array(
  242. * 'genus' => 'Citrus',
  243. * 'species' => 'sinensis',
  244. * ),
  245. * 'type_id' => array (
  246. * 'cv_id' => array (
  247. * 'name' => 'sequence',
  248. * ),
  249. * 'name' => 'gene',
  250. * 'is_obsolete' => 0
  251. * ),
  252. * );
  253. * $result = chado_select_record(
  254. * 'feature', // table to select from
  255. * $values // records to delete (see variable defn. above)
  256. * );
  257. * @endcode
  258. *
  259. * Generic Queries for any SQL:
  260. *
  261. * Often it is necessary to select from more then one table in chado or to execute
  262. * other complex queries that cannot be handled efficiently by the above functions. It is
  263. * for this reason that the chado_query( [sql string], [arguments to sub-in to the sql] )
  264. * function was created. This function allows you to execute any SQL directly on the
  265. * chado database and should be used with care. If any user input will be used in the query
  266. * make sure to put a placeholder in your SQL string and then define the value in the
  267. * arguments array. This will make sure that the user input is santized and safe through
  268. * type-checking and escaping. The following code shows an example of how to use user input
  269. * resulting from a form and would be called withing the form submit function.
  270. * @code
  271. * $sql = "SELECT F.name, CVT.name as type_name, ORG.common_name
  272. * FROM feature F
  273. * LEFT JOIN cvterm CVT ON F.type_id = CVT.cvterm_id
  274. * LEFT JOIN organism ORG ON F.organism_id = ORG.organism_id
  275. * WHERE
  276. * F.uniquename = :feature_uniquename";
  277. * $args = array( ':feature_uniquename' => $form_state['values']['uniquename'] );
  278. * $result = chado_query( $sql, $args );
  279. * foreach ($result as $r) { [Do something with the records here] }
  280. * @endcode
  281. *
  282. * If you are going to need more then a couple fields, you might want to use the
  283. * Chado Variables API (specifically chado_generate_var()) to select all
  284. * of the common fields needed including following foreign keys.
  285. *
  286. * Loading of Variables from chado data:
  287. *
  288. * These functions, chado_generate_var() and chado_expand_var(), generate objects
  289. * containing the full details of a record(s) in chado. These should be used in all
  290. * theme templates.
  291. *
  292. * This differs from the objects returned by chado_select_record in so far as all foreign key
  293. * relationships have been followed meaning you have more complete details. Thus this function
  294. * should be used whenever you need a full variable and chado_select_record should be used if
  295. * you only case about a few columns.
  296. *
  297. * The initial variable is generated by the
  298. * chado_generate_var([table], [filter criteria], [optional options])
  299. * function. An example of how to use this function is:
  300. * @code
  301. $values = array(
  302. 'name' => 'Medtr4g030710'
  303. );
  304. $features = chado_generate_var('feature', $values);
  305. * @endcode
  306. * This will return an object if there is only one feature with the name Medtr4g030710 or it will
  307. * return an array of feature objects if more than one feature has that name.
  308. *
  309. * Some tables and fields are excluded by default. To have those tables & fields added to
  310. * your variable you can use the
  311. * chado_expand_var([chado variable], [type], [what to expand], [optional options])
  312. * function. An example of how to use this function is:
  313. * @code
  314. // Get a chado object to be expanded
  315. $values = array(
  316. 'name' => 'Medtr4g030710'
  317. );
  318. $features = chado_generate_var('feature', $values);
  319. // Expand the organism node
  320. $feature = chado_expand_var($feature, 'node', 'organism');
  321. // Expand the feature.residues field
  322. $feature = chado_expand_var($feature, 'field', 'feature.residues');
  323. // Expand the feature properties (featureprop table)
  324. $feature = chado_expand_var($feature, 'table', 'featureprop');
  325. * @endcode
  326. */
  327. /**
  328. * Provides a generic routine for inserting into any Chado table
  329. *
  330. * Use this function to insert a record into any Chado table. The first
  331. * argument specifies the table for inserting and the second is an array
  332. * of values to be inserted. The array is mutli-dimensional such that
  333. * foreign key lookup values can be specified.
  334. *
  335. * @param $table
  336. * The name of the chado table for inserting
  337. * @param $values
  338. * An associative array containing the values for inserting.
  339. * @param $options
  340. * An array of options such as:
  341. * - skip_validation: TRUE or FALSE. If TRUE will skip all the validation steps and
  342. * just try to insert as is. This is much faster but results in unhandled
  343. * non user-friendly errors if the insert fails.
  344. * - return_record: by default, the function will return the record but with
  345. * the primary keys added after insertion. To simply return TRUE on success
  346. * set this option to FALSE
  347. *
  348. * @return
  349. * On success this function returns the inserted record with the new primary keys
  350. * added to the returned array. On failure, it returns FALSE.
  351. *
  352. * Example usage:
  353. * @code
  354. * $values = array(
  355. * 'organism_id' => array(
  356. * 'genus' => 'Citrus',
  357. * 'species' => 'sinensis',
  358. * ),
  359. * 'name' => 'orange1.1g000034m.g',
  360. * 'uniquename' => 'orange1.1g000034m.g',
  361. * 'type_id' => array (
  362. * 'cv_id' => array (
  363. * 'name' => 'sequence',
  364. * ),
  365. * 'name' => 'gene',
  366. * 'is_obsolete' => 0
  367. * ),
  368. * );
  369. * $result = chado_insert_record('feature',$values);
  370. * @endcode
  371. * The above code inserts a record into the feature table. The $values array is
  372. * nested such that the organism is selected by way of the organism_id foreign
  373. * key constraint by specifying the genus and species. The cvterm is also
  374. * specified using its foreign key and the cv_id for the cvterm is nested as
  375. * well.
  376. *
  377. * @ingroup tripal_chado_query_api
  378. */
  379. function chado_insert_record($table, $values, $options = array()) {
  380. $print_errors = (isset($options['print_errors'])) ? $options['print_errors'] : FALSE;
  381. if (!is_array($values)) {
  382. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  383. 'Cannot pass non array as values for inserting.', array(),
  384. array('print' => $print_errors)
  385. );
  386. return FALSE;
  387. }
  388. if (count($values)==0) {
  389. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  390. 'Cannot pass an empty array as values for inserting.',
  391. array(),array('print' => $print_errors)
  392. );
  393. return FALSE;
  394. }
  395. // set defaults for options. If we don't set defaults then
  396. // we get memory leaks when we try to access the elements
  397. if (!is_array($options)) {
  398. $options = array();
  399. }
  400. if (!array_key_exists('skip_validation', $options)) {
  401. $options['skip_validation'] = FALSE;
  402. }
  403. if (!array_key_exists('return_record', $options)) {
  404. $options['return_record'] = TRUE;
  405. }
  406. $insert_values = array();
  407. if (array_key_exists('skip_validation', $options)) {
  408. $validate = !$options['skip_validation'];
  409. }
  410. else {
  411. $validate = TRUE;
  412. }
  413. // get the table description
  414. $table_desc = chado_get_schema($table);
  415. if (!$table_desc) {
  416. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  417. 'chado_insert_record; There is no table description for !table_name',
  418. array('!table_name' => $table), array('print' => $print_errors)
  419. );
  420. return;
  421. }
  422. // iterate through the values array and create a new 'insert_values' array
  423. // that has all the values needed for insert with all foreign relationsihps
  424. // resolved.
  425. foreach ($values as $field => $value) {
  426. // make sure the field is in the table description. If not then return an error
  427. // message
  428. if (!array_key_exists($field, $table_desc['fields'])) {
  429. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  430. "chado_insert_record; The field '%field' does not exist " .
  431. "for the table '%table'. Cannot perform insert. Values: %array",
  432. array('%field' => $field, '%table' => $table, '%array' => print_r($values, 1)),
  433. array('print' => $print_errors)
  434. );
  435. return FALSE;
  436. }
  437. if (is_array($value)) {
  438. // select the value from the foreign key relationship for this value
  439. $results = chado_schema_get_foreign_key($table_desc, $field, $value);
  440. if (sizeof($results) > 1) {
  441. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  442. 'chado_insert_record: Too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)',
  443. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
  444. array('print' => $print_errors)
  445. );
  446. return FALSE;
  447. }
  448. elseif (sizeof($results) < 1) {
  449. tripal_report_error('tripal_chado', TRIPAL_DEBUG,
  450. 'chado_insert_record: no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)',
  451. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
  452. array('print' => $print_errors)
  453. );
  454. return FALSE;
  455. }
  456. else {
  457. $insert_values[$field] = $results[0];
  458. }
  459. }
  460. else {
  461. $insert_values[$field] = $value;
  462. }
  463. }
  464. if ($validate) {
  465. // check for violation of any unique constraints
  466. $ukeys = array();
  467. if (array_key_exists('unique keys', $table_desc)) {
  468. $ukeys = $table_desc['unique keys'];
  469. }
  470. $ukselect_cols = array();
  471. $ukselect_vals = array();
  472. if ($ukeys) {
  473. foreach ($ukeys as $name => $fields) {
  474. foreach ($fields as $index => $field) {
  475. // build the arrays for performing a select that will check the contraint
  476. $ukselect_cols[] = $field;
  477. if (!array_key_exists($field, $insert_values)) {
  478. if (array_key_exists('default', $table_desc['fields'][$field])) {
  479. $ukselect_vals[$field] = $table_desc['fields'][$field]['default'];
  480. }
  481. }
  482. else {
  483. $ukselect_vals[$field] = $insert_values[$field];
  484. }
  485. }
  486. // now check the constraint
  487. if (chado_select_record($table, $ukselect_cols, $ukselect_vals)) {
  488. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  489. "chado_insert_record; Cannot insert duplicate record into $table table: !values",
  490. array('!values' => print_r($values, TRUE)), array('print' => $print_errors)
  491. );
  492. return FALSE;
  493. }
  494. }
  495. }
  496. // If trying to insert a field that is the primary key, make sure it also
  497. // is unique.
  498. if (array_key_exists('primary key', $table_desc)) {
  499. $pkey = $table_desc['primary key'][0];
  500. if (array_key_exists($pkey, $insert_values)) {
  501. $coptions = array();
  502. if (chado_select_record($table, array($pkey), array($pkey => $insert_values[$pkey]), $coptions)) {
  503. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  504. 'chado_insert_record; Cannot insert duplicate primary key into !table table: !values',
  505. array('!table' => $table, '!values' => print_r($values, TRUE)),
  506. array('print' => $print_errors)
  507. );
  508. return FALSE;
  509. }
  510. }
  511. }
  512. // Make sure required fields have a value.
  513. if (!is_array($table_desc['fields'])) {
  514. $table_desc['fields'] = array();
  515. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  516. "chado_insert_record; %table missing fields: \n %schema",
  517. array('%table' => $table, '%schema' => print_r($table_desc, 1)),
  518. array('print' => $print_errors)
  519. );
  520. }
  521. foreach ($table_desc['fields'] as $field => $def) {
  522. // A field is considered missing if it cannot be NULL and there is no
  523. // default value for it or it is of type 'serial'.
  524. if (array_key_exists('NOT NULL', $def) and
  525. !array_key_exists($field, $insert_values) and
  526. !array_key_exists('default', $def) and
  527. strcmp($def['type'], serial) != 0) {
  528. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  529. "chado_insert_record; Field %table.%field cannot be NULL: %values",
  530. array('%table' => $table, '%field' => $field, '%values' => print_r($values, 1)),
  531. array('print' => $print_errors)
  532. );
  533. return FALSE;
  534. }
  535. }
  536. }
  537. // End of validation.
  538. // Now build the insert SQL statement
  539. $ifields = array(); // contains the names of the fields
  540. $itypes = array(); // contains placeholders for the sql query
  541. $ivalues = array(); // contains the values of the fields
  542. foreach ($insert_values as $field => $value) {
  543. $ifields[] = $field;
  544. if (strcmp($value, '__NULL__')==0) {
  545. $itypes[] = "NULL";
  546. }
  547. else {
  548. $itypes[] = ":$field";
  549. $ivalues[":$field"] = $value;
  550. }
  551. }
  552. // create the SQL
  553. $sql = 'INSERT INTO {' . $table . '} (' . implode(", ", $ifields) . ") VALUES (" . implode(", ", $itypes) . ")";
  554. $result = chado_query($sql, $ivalues);
  555. // if we have a result then add primary keys to return array
  556. if ($options['return_record'] == TRUE and $result) {
  557. if (array_key_exists('primary key', $table_desc) and is_array($table_desc['primary key'])) {
  558. foreach ($table_desc['primary key'] as $field) {
  559. $sql = "SELECT CURRVAL('{" . $table . "_" . $field . "_seq}')";
  560. $results = chado_query($sql);
  561. $value = $results->fetchField();
  562. if (!$value) {
  563. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  564. "chado_insert_record; not able to retrieve primary key after insert: %sql",
  565. array('%sql' => $sql),
  566. array('print' => $print_errors)
  567. );
  568. return FALSE;
  569. }
  570. $values[$field] = $value;
  571. }
  572. }
  573. return $values;
  574. }
  575. elseif ($options['return_record'] == FALSE and $result) {
  576. return TRUE;
  577. }
  578. else {
  579. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  580. 'chado_insert_record; Cannot insert record into "%table": %values',
  581. array('%table' => $table, '%values' => print_r($values, 1)),
  582. array('print' => $print_errors)
  583. );
  584. return FALSE;
  585. }
  586. return FALSE;
  587. }
  588. /**
  589. * Provides a generic routine for updating into any Chado table
  590. *
  591. * Use this function to update a record in any Chado table. The first
  592. * argument specifies the table for inserting, the second is an array
  593. * of values to matched for locating the record for updating, and the third
  594. * argument give the values to update. The arrays are mutli-dimensional such
  595. * that foreign key lookup values can be specified.
  596. *
  597. * @param $table
  598. * The name of the chado table for inserting
  599. * @param $match
  600. * An associative array containing the values for locating a record to update.
  601. * @param $values
  602. * An associative array containing the values for updating.
  603. * @param $options
  604. * An array of options such as:
  605. * - return_record: by default, the function will return the TRUE if the record
  606. * was succesfully updated. However, set this option to TRUE to return the
  607. * record that was updated. The returned record will have the fields provided
  608. * but the primary key (if available for the table) will be added to the record.
  609. * @return
  610. * On success this function returns TRUE. On failure, it returns FALSE.
  611. *
  612. * Example usage:
  613. * @code
  614. $umatch = array(
  615. 'organism_id' => array(
  616. 'genus' => 'Citrus',
  617. 'species' => 'sinensis',
  618. ),
  619. 'uniquename' => 'orange1.1g000034m.g7',
  620. 'type_id' => array (
  621. 'cv_id' => array (
  622. 'name' => 'sequence',
  623. ),
  624. 'name' => 'gene',
  625. 'is_obsolete' => 0
  626. ),
  627. );
  628. $uvalues = array(
  629. 'name' => 'orange1.1g000034m.g',
  630. 'type_id' => array (
  631. 'cv_id' => array (
  632. 'name' => 'sequence',
  633. ),
  634. 'name' => 'mRNA',
  635. 'is_obsolete' => 0
  636. ),
  637. );
  638. * $result = chado_update_record('feature',$umatch,$uvalues);
  639. * @endcode
  640. * The above code species that a feature with a given uniquename, organism_id,
  641. * and type_id (the unique constraint for the feature table) will be updated.
  642. * The organism_id is specified as a nested array that uses the organism_id
  643. * foreign key constraint to lookup the specified values to find the exact
  644. * organism_id. The same nested struture is also used for specifying the
  645. * values to update. The function will find the record that matches the
  646. * columns specified and update the record with the avlues in the $uvalues array.
  647. *
  648. * @TODO: Support Complex filtering as is done in chado_select_record();
  649. *
  650. * @ingroup tripal_chado_query_api
  651. */
  652. function chado_update_record($table, $match, $values, $options = NULL) {
  653. $print_errors = (isset($options['print_errors'])) ? $options['print_errors'] : FALSE;
  654. if (!is_array($values)) {
  655. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  656. 'Cannot pass non array as values for updating.',
  657. array(), array('print' => $print_errors)
  658. );
  659. return FALSE;
  660. }
  661. if (count($values)==0) {
  662. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  663. 'Cannot pass an empty array as values for updating.',
  664. array(), array('print' => $print_errors)
  665. );
  666. return FALSE;
  667. }
  668. if (!is_array($match)) {
  669. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  670. 'Cannot pass non array as values for matching.',
  671. array(), array('print' => $print_errors)
  672. );
  673. return FALSE;
  674. }
  675. if (count($match)==0) {
  676. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  677. 'Cannot pass an empty array as values for matching.',
  678. array(), array('print' => $print_errors)
  679. );
  680. return FALSE;
  681. }
  682. // set defaults for options. If we don't set defaults then
  683. // we get memory leaks when we try to access the elements
  684. if (!is_array($options)) {
  685. $options = array();
  686. }
  687. if (!array_key_exists('return_record', $options)) {
  688. $options['return_record'] = FALSE;
  689. }
  690. $update_values = array(); // contains the values to be updated
  691. $update_matches = array(); // contains the values for the where clause
  692. // get the table description
  693. $table_desc = chado_get_schema($table);
  694. if (!$table_desc) {
  695. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  696. 'The table name, %table, does not exist.',
  697. array('%table', $table), array('print' => $print_errors)
  698. );
  699. return FALSE;
  700. }
  701. // if the user wants us to return the record then we need to get the
  702. // unique primary key if one exists. That way we can add it to the
  703. // values that get returned at the end of the function
  704. $pkeys = array();
  705. if ($options['return_record'] == TRUE) {
  706. if (array_key_exists('primary key', $table_desc) and is_array($table_desc['primary key'])) {
  707. $columns = array();
  708. $stmt_suffix = '';
  709. foreach ($table_desc['primary key'] as $field) {
  710. $columns[] = $field;
  711. $stmt_suffix .= substr($field, 0, 2);
  712. }
  713. $options2 = array();
  714. $results = chado_select_record($table, $columns, $match, $options2);
  715. if (count($results) > 0) {
  716. foreach ($results as $index => $pkey) {
  717. $pkeys[] = $pkey;
  718. }
  719. }
  720. }
  721. }
  722. // get the values needed for matching in the SQL statement
  723. foreach ($match as $field => $value) {
  724. if (is_array($value)) {
  725. $results = chado_schema_get_foreign_key($table_desc, $field, $value);
  726. if (sizeof($results) > 1) {
  727. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  728. 'chado_update_record: When trying to find record to update, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)',
  729. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
  730. array('print' => $print_errors)
  731. );
  732. return FALSE;
  733. }
  734. elseif (sizeof($results) < 1) {
  735. tripal_report_error('tripal_chado', TRIPAL_DEBUG,
  736. 'chado_update_record: When trying to find record to update, no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)',
  737. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
  738. array('print' => $print_errors)
  739. );
  740. return FALSE;
  741. }
  742. else {
  743. $update_matches[$field] = $results[0];
  744. }
  745. }
  746. else {
  747. $update_matches[$field] = $value;
  748. }
  749. }
  750. // get the values used for updating
  751. foreach ($values as $field => &$value) {
  752. if (is_array($value)) {
  753. $foreign_options = array();
  754. // select the value from the foreign key relationship for this value
  755. $results = chado_schema_get_foreign_key($table_desc, $field, $value, $foreign_options);
  756. if (sizeof($results) > 1) {
  757. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  758. 'chado_update_record: When trying to find update values, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)',
  759. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
  760. array('print' => $print_errors)
  761. );
  762. return FALSE;
  763. }
  764. elseif (sizeof($results) < 1) {
  765. tripal_report_error('tripal_chado', TRIPAL_DEBUG,
  766. 'chado_update_record: When trying to find update values, no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)',
  767. array('!foreign_key' => $field, '!criteria' => print_r($value,TRUE)),
  768. array('print' => $print_errors)
  769. );
  770. return FALSE;
  771. }
  772. else {
  773. $update_values[$field] = $results[0];
  774. }
  775. }
  776. else {
  777. $update_values[$field] = $value;
  778. }
  779. }
  780. // now build the SQL statement
  781. $sql = 'UPDATE {' . $table . '} SET ';
  782. $args = array(); // arguments passed to chado_query
  783. foreach ($update_values as $field => $value) {
  784. if (strcmp($value, '__NULL__') == 0) {
  785. $sql .= " $field = NULL, ";
  786. }
  787. else {
  788. $sql .= " $field = :$field, ";
  789. $args[":$field"] = $value;
  790. }
  791. }
  792. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing comma & space
  793. $sql .= " WHERE ";
  794. foreach ($update_matches as $field => $value) {
  795. if (strcmp($value, '__NULL__')==0) {
  796. $sql .= " $field = NULL AND ";
  797. }
  798. else {
  799. $sql .= " $field = :$field AND ";
  800. $args[":$field"] = $value;
  801. }
  802. }
  803. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND'
  804. $result = chado_query($sql, $args);
  805. // if we have a result then add primary keys to return array
  806. if ($options['return_record'] == TRUE and $result) {
  807. // only if we have a single result do we want to add the primary keys to the values
  808. // array. If the update matched many records we can't add the pkeys
  809. if (count($pkeys) == 1) {
  810. foreach ($pkeys as $index => $pkey) {
  811. foreach ($pkey as $field => $fvalue) {
  812. $values[$field] = $fvalue;
  813. }
  814. }
  815. }
  816. return $values;
  817. }
  818. elseif ($options['return_record'] == FALSE and $result) {
  819. return TRUE;
  820. }
  821. else {
  822. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  823. "chado_update_record: Cannot update record in %table table. \nMatch: %match \nValues: %values",
  824. array('%table' => table, '%match' => print_r($match,TRUE), '%values' => print_r($values, 1)),
  825. array('print' => $print_errors)
  826. );
  827. return FALSE;
  828. }
  829. return FALSE;
  830. }
  831. /**
  832. * Provides a generic function for deleting a record(s) from any chado table
  833. *
  834. * Use this function to delete a record(s) in any Chado table. The first
  835. * argument specifies the table to delete from and the second is an array
  836. * of values to match for locating the record(s) to be deleted. The arrays
  837. * are mutli-dimensional such that foreign key lookup values can be specified.
  838. *
  839. * @param $table
  840. * The name of the chado table for inserting
  841. * @param $match
  842. * An associative array containing the values for locating a record to update.
  843. * @param $options
  844. * Currently there are no options
  845. * @return
  846. * On success this function returns TRUE. On failure, it returns FALSE.
  847. *
  848. * Example usage:
  849. * @code
  850. $umatch = array(
  851. 'organism_id' => array(
  852. 'genus' => 'Citrus',
  853. 'species' => 'sinensis',
  854. ),
  855. 'uniquename' => 'orange1.1g000034m.g7',
  856. 'type_id' => array (
  857. 'cv_id' => array (
  858. 'name' => 'sequence',
  859. ),
  860. 'name' => 'gene',
  861. 'is_obsolete' => 0
  862. ),
  863. );
  864. $uvalues = array(
  865. 'name' => 'orange1.1g000034m.g',
  866. 'type_id' => array (
  867. 'cv_id' => array (
  868. 'name' => 'sequence',
  869. ),
  870. 'name' => 'mRNA',
  871. 'is_obsolete' => 0
  872. ),
  873. );
  874. * $result = chado_update_record('feature', $umatch, $uvalues);
  875. * @endcode
  876. * The above code species that a feature with a given uniquename, organism_id,
  877. * and type_id (the unique constraint for the feature table) will be deleted.
  878. * The organism_id is specified as a nested array that uses the organism_id
  879. * foreign key constraint to lookup the specified values to find the exact
  880. * organism_id. The same nested struture is also used for specifying the
  881. * values to update. The function will find all records that match the
  882. * columns specified and delete them.
  883. *
  884. * @TODO: Support Complex filtering as is done in chado_select_record();
  885. *
  886. * @ingroup tripal_chado_query_api
  887. */
  888. function chado_delete_record($table, $match, $options = NULL) {
  889. $print_errors = (isset($options['print_errors'])) ? $options['print_errors'] : FALSE;
  890. if (!is_array($match)) {
  891. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  892. 'Cannot pass non array as values for matching.', array());
  893. return FALSE;
  894. }
  895. if (count($match)==0) {
  896. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  897. 'Cannot pass an empty array as values for matching.', array());
  898. return FALSE;
  899. }
  900. // set defaults for options. If we don't set defaults then
  901. // we get memory leaks when we try to access the elements
  902. if (!is_array($options)) {
  903. $options = array();
  904. }
  905. $delete_matches = array(); // contains the values for the where clause
  906. // get the table description
  907. $table_desc = chado_get_schema($table);
  908. $fields = $table_desc['fields'];
  909. if (empty($table_desc)) {
  910. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  911. 'chado_insert_record; There is no table description for !table_name',
  912. array('!table_name' => $table), array('print' => $print_errors)
  913. );
  914. }
  915. // get the values needed for matching in the SQL statement
  916. foreach ($match as $field => $value) {
  917. if (is_array($value)) {
  918. // if the user has specified an array of values to delete rather than
  919. // FK relationships the keep those in our match
  920. if (array_values($value) === $value) {
  921. $delete_matches[$field] = $value;
  922. }
  923. else {
  924. $results = chado_schema_get_foreign_key($table_desc, $field, $value);
  925. if (sizeof($results) > 1) {
  926. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  927. 'chado_delete_record: When trying to find record to delete, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)',
  928. array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)));
  929. return FALSE;
  930. }
  931. elseif (sizeof($results) < 1) {
  932. //tripal_report_error('tripal_chado', 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)));
  933. }
  934. else {
  935. $delete_matches[$field] = $results[0];
  936. }
  937. }
  938. }
  939. else {
  940. $delete_matches[$field] = $value;
  941. }
  942. }
  943. // now build the SQL statement
  944. $sql = 'DELETE FROM {' . $table . '} WHERE ';
  945. $args = array();
  946. foreach ($delete_matches as $field => $value) {
  947. // if we have an array values then this is an "IN" clasue.
  948. if (count($value) > 1) {
  949. $sql .= "$field IN (";
  950. $index = 0;
  951. foreach ($value as $v) {
  952. $sql .= ":$field" . $index . ", ";
  953. $args[":$field" . $index] = $v;
  954. $index++;
  955. }
  956. $sql = drupal_substr($sql, 0, -2); // get rid of trailing ', '
  957. $sql .= ") AND ";
  958. }
  959. else {
  960. if (strcmp($value, '__NULL__') == 0) {
  961. $sql .= " $field = NULL AND ";
  962. }
  963. else {
  964. $sql .= " $field = :$field AND ";
  965. $args[":$field"] = $value;
  966. }
  967. }
  968. }
  969. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND'
  970. // finally perform the delete. If successful, return the updated record
  971. $result = chado_query($sql, $args);
  972. if ($result) {
  973. return TRUE;
  974. }
  975. else {
  976. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  977. "Cannot delete record in $table table. Match:" . print_r($match, 1) . ". Values: " . print_r($values, 1), array());
  978. return FALSE;
  979. }
  980. return FALSE;
  981. }
  982. /**
  983. * Provides a generic routine for selecting data from a Chado table
  984. *
  985. * Use this function to perform a simple select from any Chado table.
  986. *
  987. * @param $table
  988. * The name of the chado table for inserting
  989. * @param $columns
  990. * An array of column names
  991. * @param $values
  992. * An associative array containing the values for filtering the results. In the
  993. * case where multiple values for the same time are to be selected an additional
  994. * entry for the field should appear for each value. If you need to filter
  995. * results using more complex methods see the 'Complex Filtering' section below.
  996. * @param $options
  997. * An associative array of additional options where the key is the option
  998. * and the value is the value of that option.
  999. *
  1000. * Additional Options Include:
  1001. * - has_record
  1002. * Set this argument to 'TRUE' to have this function return a numeric
  1003. * value for the number of records rather than the array of records. this
  1004. * can be useful in 'if' statements to check the presence of particula records.
  1005. * - return_sql
  1006. * Set this to 'TRUE' to have this function return an array where the first
  1007. * element is the sql that would have been run and the second is an array of
  1008. * arguments.
  1009. * - case_insensitive_columns
  1010. * An array of columns to do a case insensitive search on.
  1011. * - regex_columns
  1012. * An array of columns where the value passed in should be treated as a regular expression
  1013. * - order_by
  1014. * An associative array containing the column names of the table as keys
  1015. * and the type of sort (i.e. ASC, DESC) as the values. The results in the
  1016. * query will be sorted by the key values in the direction listed by the value
  1017. * - is_duplicate: TRUE or FALSE. Checks the values submited to see if
  1018. * they violate any of the unique constraints. If not, the record
  1019. * is returned, if so, FALSE is returned.
  1020. * - pager: Use this option if it is desired to return only a subset of results
  1021. * so that they may be shown with in a Drupal-style pager. This should be
  1022. * an array with two keys: 'limit' and 'element'. The value of 'limit'
  1023. * should specify the number of records to return and 'element' is a
  1024. * unique integer to differentiate between pagers when more than one
  1025. * appear on a page. The 'element' should start with zero and increment by
  1026. * one for each pager.
  1027. * -limit: Specifies the number of records to return.
  1028. * -offset: Indicates the number of records to skip before returning records.
  1029. *
  1030. * @return
  1031. * An array of results, FALSE if the query was not executed
  1032. * correctly, an empty array if no records were matched, or the number of records
  1033. * in the dataset if $has_record is set.
  1034. * If the option 'is_duplicate' is provided and the record is a duplicate it
  1035. * will return the duplicated record. If the 'has_record' option is provided
  1036. * a value of TRUE will be returned if a record exists and FALSE will bee
  1037. * returned if there are not records.
  1038. *
  1039. * Example usage:
  1040. * @code
  1041. * $columns = array('feature_id', 'name');
  1042. * $values = array(
  1043. * 'organism_id' => array(
  1044. * 'genus' => 'Citrus',
  1045. * 'species' => array('sinensis', 'clementina'),
  1046. * ),
  1047. * 'uniquename' => 'orange1.1g000034m.g',
  1048. * 'type_id' => array (
  1049. * 'cv_id' => array (
  1050. * 'name' => 'sequence',
  1051. * ),
  1052. * 'name' => 'gene',
  1053. * 'is_obsolete' => 0
  1054. * ),
  1055. * );
  1056. * $options = array(
  1057. * 'order_by' => array(
  1058. * 'name' => 'ASC'
  1059. * ),
  1060. * );
  1061. * $result = chado_select_record('feature',$columns,$values,$options);
  1062. * @endcode
  1063. * The above code selects a record from the feature table using the three fields
  1064. * that uniquely identify a feature. The $columns array simply lists the columns
  1065. * to select. The $values array is nested such that the organism is identified by
  1066. * way of the organism_id foreign key constraint by specifying the genus and
  1067. * species. The cvterm is also specified using its foreign key and the cv_id
  1068. * for the cvterm is nested as well. In the example above, two different species
  1069. * are allowed to match
  1070. *
  1071. * Complex Filtering:
  1072. * All of the documentation above supports filtering based on 'is equal to'
  1073. * or 'is NULL'. If your criteria doesn't fall into one of these two categories
  1074. * then you need to provide an array with additional details such as the operator
  1075. * as well as the value. An example follows and will be discussed in detail.
  1076. * @code
  1077. $columns = array('feature_id', 'fmin', 'fmax');
  1078. // Regular criteria specifying the parent feature to retrieve locations from.
  1079. $values = array(
  1080. 'srcfeature_id' => array(
  1081. 'uniquename' => 'MtChr01'
  1082. 'type_id' => array(
  1083. 'name' => 'pseudomolecule'
  1084. ),
  1085. ),
  1086. );
  1087. // Complex filtering to specify the range to return locations from.
  1088. $values['fmin'][] = array(
  1089. 'op' => '>',
  1090. 'data' => 15
  1091. );
  1092. $values['fmin'][] = array(
  1093. 'op' => '<',
  1094. 'data' => 100
  1095. );
  1096. $results = chado_select_record('featureloc', $columns, $values);
  1097. * @endcode
  1098. * The above code example will return all of the name, start and end of all
  1099. * the features that start within MtChr1:15-100bp. Note that complex filtering
  1100. * can be used in conjunction with basic filtering and that multiple criteria,
  1101. * even for the same field can be entered.
  1102. *
  1103. * @ingroup tripal_chado_query_api
  1104. */
  1105. function chado_select_record($table, $columns, $values, $options = NULL) {
  1106. // Set defaults for options. If we don't set defaults then
  1107. // we get memory leaks when we try to access the elements.
  1108. if (!is_array($options)) {
  1109. $options = array();
  1110. }
  1111. if (!array_key_exists('case_insensitive_columns', $options)) {
  1112. $options['case_insensitive_columns'] = array();
  1113. }
  1114. if (!array_key_exists('regex_columns', $options)) {
  1115. $options['regex_columns'] = array();
  1116. }
  1117. if (!array_key_exists('order_by', $options)) {
  1118. $options['order_by'] = array();
  1119. }
  1120. if (!array_key_exists('return_sql', $options)) {
  1121. $options['return_sql'] = FALSE;
  1122. }
  1123. if (!array_key_exists('has_record', $options)) {
  1124. $options['has_record'] = FALSE;
  1125. }
  1126. if (!array_key_exists('is_duplicate', $options)) {
  1127. $options['is_duplicate'] = FALSE;
  1128. }
  1129. $pager = array();
  1130. if (array_key_exists('pager', $options)) {
  1131. $pager = $options['pager'];
  1132. }
  1133. $print_errors = FALSE;
  1134. if (isset($options['print_errors'])) {
  1135. $print_errors = $options['print_errors'];
  1136. }
  1137. // Check that our columns and values arguments are proper arrays.
  1138. if (!is_array($columns)) {
  1139. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  1140. 'chado_select_record; the $columns argument must be an array. Columns:%columns',
  1141. array('%columns' => print_r($columns, TRUE)),
  1142. array('print' => $print_errors)
  1143. );
  1144. return FALSE;
  1145. }
  1146. if (!is_array($values)) {
  1147. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  1148. 'chado_select_record; the $values argument must be an array. Values:%values',
  1149. array('%values' => print_r($values, TRUE)),
  1150. array('print' => $print_errors)
  1151. );
  1152. return FALSE;
  1153. }
  1154. // Get the table description.
  1155. $table_desc = chado_get_schema($table);
  1156. if (!is_array($table_desc)) {
  1157. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  1158. 'chado_insert_record; There is no table description for !table_name',
  1159. array('!table_name' => $table), array('print' => $print_errors)
  1160. );
  1161. return FALSE;
  1162. }
  1163. $select = '';
  1164. $from = '';
  1165. $where = array();
  1166. $args = array();
  1167. if ($options['is_duplicate'] and array_key_exists('unique keys', $table_desc)) {
  1168. $ukeys = $table_desc['unique keys'];
  1169. $has_results = 0;
  1170. // iterate through the unique constraints and reset the values and columns
  1171. // arrays to only include these fields
  1172. foreach ($ukeys as $cname => $fields) {
  1173. if ($has_results) {
  1174. continue;
  1175. }
  1176. $new_values = array();
  1177. $new_columns = array();
  1178. $new_options = array();
  1179. $has_pkey = 0;
  1180. // include the primary key in the results returned
  1181. if (array_key_exists('primary key', $table_desc)) {
  1182. $has_pkey = 1;
  1183. $pkeys = $table_desc['primary key'];
  1184. foreach ($pkeys as $index => $key) {
  1185. array_push($new_columns, $key);
  1186. }
  1187. }
  1188. // recreate the $values and $columns arrays
  1189. foreach ($fields as $field) {
  1190. if (array_key_exists($field, $values)) {
  1191. $new_values[$field] = $values[$field];
  1192. // if there is no primary key then use the unique contraint fields
  1193. if (!$has_pkey) {
  1194. array_push($new_columns, $field);
  1195. }
  1196. }
  1197. // if the field doesn't exist in the values array then
  1198. // substitute any default values
  1199. elseif (array_key_exists('default', $table_desc['fields'][$field])) {
  1200. $new_values[$field] = $table_desc['fields'][$field]['default'];
  1201. if (!$has_pkey) {
  1202. array_push($new_columns, $field);
  1203. }
  1204. }
  1205. // if there is no value (default or otherwise) check if this field is
  1206. // allowed to be null
  1207. elseif (!$table_desc['fields'][$field]['not null']) {
  1208. $new_values[$field] = NULL;
  1209. if (!$has_pkey) {
  1210. array_push($new_columns, $field);
  1211. }
  1212. }
  1213. // if the array key doesn't exist in the values given by the caller
  1214. // and there is no default value then we cannot check if the record
  1215. // is a duplicate so return FALSE
  1216. else {
  1217. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  1218. 'chado_select_record: There is no value for %field thus we cannot ' .
  1219. 'check if this record for table, %table, is unique. %values',
  1220. array('%field' => $field, '%table' => $table, '%values' => print_r($values, TRUE)),
  1221. array('print' => $print_errors));
  1222. return FALSE;
  1223. }
  1224. }
  1225. $results = chado_select_record($table, $new_columns, $new_values, $new_options);
  1226. // if we have a duplicate record then return the results
  1227. if (count($results) > 0) {
  1228. $has_results = 1;
  1229. }
  1230. unset($new_columns);
  1231. unset($new_values);
  1232. unset($new_options);
  1233. }
  1234. if ($options['has_record'] and $has_results) {
  1235. return TRUE;
  1236. }
  1237. else {
  1238. return $results;
  1239. }
  1240. }
  1241. // Process the values array into where clauses and retrieve foreign keys. The
  1242. // $where array should always be an integer-indexed array with each value
  1243. // being an array with a 'field', 'op', and 'data' keys with all foreign keys
  1244. // followed.
  1245. foreach ($values as $field => $value) {
  1246. // Require the field be in the table description.
  1247. if (!array_key_exists($field, $table_desc['fields'])) {
  1248. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  1249. 'chado_select_record: The field "%field" does not exist for the table "%table". Cannot perform query. Values: %array',
  1250. array('%field' => $field, '%table' => $table, '%array' => print_r($values, 1)),
  1251. array('print' => $print_errors)
  1252. );
  1253. return array();
  1254. }
  1255. $select[] = $field;
  1256. // CASE 1: We have an array for a value.
  1257. if (is_array($value)) {
  1258. // CASE 1a: If there is only one element in the array, treat it the same
  1259. // as a non-array value.
  1260. if (count($value) == 1 AND is_int(key($value))) {
  1261. $value = array_pop($value);
  1262. $op = '=';
  1263. chado_select_record_check_value_type($op, $value, $table_desc['fields'][$field]['type']);
  1264. $where[] = array(
  1265. 'field' => $field,
  1266. 'op' => $op,
  1267. 'data' => $value
  1268. );
  1269. }
  1270. // CASE 1b: If there is a 'data' key in the array then we have the new
  1271. // complex filtering format with a single criteria.
  1272. elseif (isset($value['data']) AND isset($value['op'])) {
  1273. $value['field'] = $field;
  1274. $where[] = $value;
  1275. }
  1276. // CASE 1c: If we have an integer indexed array and the first element is
  1277. // not an array then we have a simple array of values to be used for an IN clause.
  1278. elseif (is_int(key($value)) AND !is_array(current($value))) {
  1279. $where[] = array(
  1280. 'field' => $field,
  1281. 'op' => 'IN',
  1282. 'data' => $value
  1283. );
  1284. }
  1285. // We have a multi-dimensional array: 2 cases...
  1286. else {
  1287. // CASE 1d: If there is a multi-dimensional array with each sub-array
  1288. // containing a data key then we have the new complex filtering format
  1289. // with multiple criteria.
  1290. if (isset($value[0]['data']) AND isset($value[0]['op'])) {
  1291. foreach ($value as $subvalue) {
  1292. $subvalue['field'] = $field;
  1293. $where[] = $subvalue;
  1294. }
  1295. }
  1296. // CASE 1e: We have a multi-dimensional array that doesn't fit any of the
  1297. // above cases then we have a foreign key definition to follow.
  1298. else {
  1299. // Select the value from the foreign key relationship for this value.
  1300. $foreign_options = array(
  1301. 'regex_columns' => $options['regex_columns'],
  1302. );
  1303. $results = chado_schema_get_foreign_key($table_desc, $field, $value, $foreign_options);
  1304. // Ensure that looking up the foreign key didn't fail in an error.
  1305. if ($results === FALSE OR $results === NULL) {
  1306. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  1307. 'chado_select_record: could not follow the foreign key definition
  1308. for %field where the definition supplied was %value',
  1309. array('%field' => $field, '%value' => print_r($value, TRUE))
  1310. );
  1311. return array();
  1312. }
  1313. // Ensure that there were results returned.
  1314. elseif (count($results)==0) {
  1315. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  1316. 'chado_select_record: the foreign key definition for \'%field\' on table \'%table\' '.
  1317. 'returned no results where the definition supplied was %value',
  1318. array('%field' => $field, '%table' => $table, '%value' => print_r($value, TRUE))
  1319. );
  1320. return array();
  1321. }
  1322. // If there was only a single resutlt then add it using an op of =.
  1323. elseif (count($results) == 1) {
  1324. $results = array_pop($results);
  1325. $op = '=';
  1326. chado_select_record_check_value_type($op, $results, $table_desc['fields'][$field]['type']);
  1327. $where[] = array(
  1328. 'field' => $field,
  1329. 'op' => $op,
  1330. 'data' => $results
  1331. );
  1332. }
  1333. // Otherwise multiple results were returned so we want to form an
  1334. // IN (x, y, z) expression.
  1335. else {
  1336. $where[] = array(
  1337. 'field' => $field,
  1338. 'op' => 'IN',
  1339. 'data' => $results
  1340. );
  1341. }
  1342. }
  1343. }
  1344. }
  1345. // CASE 2: We have a single value.
  1346. else {
  1347. $op = '=';
  1348. chado_select_record_check_value_type($op, $value, $table_desc['fields'][$field]['type']);
  1349. $where[] = array(
  1350. 'field' => $field,
  1351. 'op' => $op,
  1352. 'data' => $value
  1353. );
  1354. }
  1355. // Support Deprecated method for regex conditions.
  1356. $current_key = key($where);
  1357. if (in_array($field, $options['regex_columns'])) {
  1358. $where[$current_key]['op'] = '~*';
  1359. }
  1360. }
  1361. // Now build the SQL.
  1362. if (empty($where)) {
  1363. // Sometimes want to select everything.
  1364. $sql = "SELECT " . implode(', ', $columns) . " ";
  1365. $sql .= 'FROM {' . $table . '} ';
  1366. }
  1367. else {
  1368. $sql = "SELECT " . implode(', ', $columns) . " ";
  1369. $sql .= 'FROM {' . $table . '} ';
  1370. // If $values is empty then we want all results so no where clause.
  1371. if (!empty($values)) {
  1372. $sql .= "WHERE ";
  1373. }
  1374. foreach ($where as $clause_num => $value_def) {
  1375. switch ($value_def['op']) {
  1376. // Deal with 'field IN (x, y, z)' where clauses.
  1377. case 'IN':
  1378. $sql .= $value_def['field'] . " IN (";
  1379. $index = 0;
  1380. foreach ($value_def['data'] as $v) {
  1381. $placeholder = ':' . $value_def['field'] . $clause_num .'_' . $index;
  1382. $sql .= $placeholder . ', ';
  1383. $args[$placeholder] = $v;
  1384. $index++;
  1385. }
  1386. $sql = drupal_substr($sql, 0, -2); // remove trailing ', '
  1387. $sql .= ") AND ";
  1388. break;
  1389. // Deal with IS NULL.
  1390. case 'IS NULL':
  1391. $sql .= $value_def['field'] . ' IS NULL AND ';
  1392. break;
  1393. // Default is [field] [op] [data].
  1394. default:
  1395. $placeholder = ':'. $value_def['field'] . $clause_num;
  1396. // Support case insensitive columns.
  1397. if (in_array($value_def['field'], $options['case_insensitive_columns'])) {
  1398. $sql .= 'lower(' . $value_def['field'] .') '. $value_def['op'] .' lower('. $placeholder . ') AND ';
  1399. }
  1400. else {
  1401. $sql .= $value_def['field'] .' '. $value_def['op'] .' '. $placeholder . ' AND ';
  1402. }
  1403. $args[$placeholder] = $value_def['data'];
  1404. }
  1405. } // end foreach item in where clause.
  1406. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND '
  1407. } // end if (empty($where)){ } else {
  1408. // Add any ordering of the results to the SQL statement.
  1409. if (count($options['order_by']) > 0) {
  1410. $sql .= " ORDER BY ";
  1411. foreach ($options['order_by'] as $field => $dir) {
  1412. $sql .= "$field $dir, ";
  1413. }
  1414. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing ', '
  1415. }
  1416. // Limit the records returned
  1417. if (array_key_exists('limit', $options) and is_numeric($options['limit'])) {
  1418. $sql .= " LIMIT " . $options['limit'];
  1419. if (array_key_exists('offset', $options) and is_numeric($options['offset'])) {
  1420. $sql .= " OFFSET " . $options['offset'];
  1421. }
  1422. }
  1423. // if the caller has requested the SQL rather than the results then do so.
  1424. if ($options['return_sql'] == TRUE) {
  1425. return array('sql' => $sql, 'args' => $args);
  1426. }
  1427. if (array_key_exists('limit', $pager)) {
  1428. $total_records = 0;
  1429. $resource = chado_pager_query($sql, $args, $pager['limit'], $pager['element'], NULL, $total_records);
  1430. }
  1431. else {
  1432. $resource = chado_query($sql, $args);
  1433. }
  1434. // Format results into an array.
  1435. $results = array();
  1436. foreach ($resource as $r) {
  1437. $results[] = $r;
  1438. }
  1439. if ($options['has_record']) {
  1440. return count($results);
  1441. }
  1442. return $results;
  1443. }
  1444. /**
  1445. * Helper Function: check that the value is the correct type.
  1446. *
  1447. * This function is used by chado_select_record() when building the $where
  1448. * clause array to ensure that any single values are the correct type based
  1449. * on the table definition. Furthermore, it ensures that NULL's are caught
  1450. * changing the operator to 'IS NULL'.
  1451. * @code
  1452. $op = '=';
  1453. chado_select_record_check_value_type($op, $value, $table_desc['fields'][$field]['type']);
  1454. $where[] = array(
  1455. 'field' => $field,
  1456. 'op' => $op,
  1457. 'data' => $value
  1458. );
  1459. * @endcode
  1460. *
  1461. * @param $op
  1462. * The operator being used. This is mostly passed in to allow it to be changed
  1463. * if a NULL value is detected.
  1464. * @param $value
  1465. * The value to be checked and adjusted.
  1466. * @param $type
  1467. * The type from the table definition that's used to determine the type of
  1468. * value.
  1469. */
  1470. function chado_select_record_check_value_type(&$op, &$value, $type) {
  1471. if ($value === NULL) {
  1472. $op = 'IS NULL';
  1473. }
  1474. elseif ($type == 'int') {
  1475. $value = (int) $value;
  1476. }
  1477. }
  1478. /**
  1479. * Use this function instead of db_query() to avoid switching databases
  1480. * when making query to the chado database
  1481. *
  1482. * Will use a chado persistent connection if it already exists
  1483. *
  1484. * @param $sql
  1485. * The sql statement to execute
  1486. *
  1487. * @param $args
  1488. * The array of arguments, with the same structure as passed to
  1489. * the db_query() function of Drupal.
  1490. *
  1491. * @return
  1492. * DatabaseStatementInterface A prepared statement object, already executed.
  1493. *
  1494. * Example usage:
  1495. * @code
  1496. * $sql = "SELECT F.name, CVT.name as type_name, ORG.common_name
  1497. * FROM {feature} F
  1498. * LEFT JOIN {cvterm} CVT ON F.type_id = CVT.cvterm_id
  1499. * LEFT JOIN {organism} ORG ON F.organism_id = ORG.organism_id
  1500. * WHERE
  1501. * F.uniquename = :feature_uniquename";
  1502. * $args = array( ':feature_uniquename' => $form_state['values']['uniquename'] );
  1503. * $result = chado_query( $sql, $args );
  1504. * foreach ($result as $r) { [Do something with the records here] }
  1505. * @endcode
  1506. *
  1507. * @ingroup tripal_chado_query_api
  1508. */
  1509. function chado_query($sql, $args = array()) {
  1510. $is_local = $GLOBALS["chado_is_local"];
  1511. // Args should be an array
  1512. if (!is_array($args)) {
  1513. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  1514. 'chado_query; Need to pass an array to chado_query, "%value" passed instead. Query: %query',
  1515. array('%value' => $args, '%query' => $sql)
  1516. );
  1517. return FALSE;
  1518. }
  1519. // if Chado is local to the database then prefix the Chado table
  1520. // names with 'chado'.
  1521. if ($is_local) {
  1522. $sql = preg_replace('/\n/', '', $sql); // remove carriage returns
  1523. $sql = preg_replace('/\{(.*?)\}/', 'chado.$1', $sql);
  1524. // the featureloc table has some indexes that use function that call other functions
  1525. // and those calls do not reference a schema, therefore, any tables with featureloc
  1526. // must automaticaly have the chado schema set as active to find
  1527. if (preg_match('/chado.featureloc/i', $sql) or preg_match('/chado.feature/i', $sql)) {
  1528. $previous_db = chado_set_active('chado') ;
  1529. $results = db_query($sql, $args);
  1530. chado_set_active($previous_db);
  1531. }
  1532. // for all other tables we should have everything in scope so just run the query
  1533. else {
  1534. $results = db_query($sql, $args);
  1535. }
  1536. }
  1537. // if Chado is not local to the Drupal database then we have to
  1538. // switch to another database
  1539. else {
  1540. $previous_db = chado_set_active('chado') ;
  1541. $results = db_query($sql, $args);
  1542. chado_set_active($previous_db);
  1543. }
  1544. return $results;
  1545. }
  1546. /**
  1547. * Use this function instead of pager_query() when selecting a
  1548. * subset of records from a Chado table.
  1549. *
  1550. * @param $query
  1551. * The SQL statement to execute, this is followed by a variable number of args
  1552. * used as substitution values in the SQL statement.
  1553. * @param $args
  1554. * The array of arguments for the query. They keys are the placeholders
  1555. * @param $limit
  1556. * The number of query results to display per page.
  1557. * @param $element
  1558. * An numeric identifier used to distinguish between multiple pagers on one page.
  1559. * @param $count_query
  1560. * An SQL query used to count matching records.
  1561. *
  1562. * @returns
  1563. * A database query result resource or FALSE if the query was not
  1564. * executed correctly
  1565. *
  1566. * @ingroup tripal_chado_query_api
  1567. */
  1568. function chado_pager_query($query, $args, $limit, $element, $count_query = '') {
  1569. // get the page and offset for the pager
  1570. $page = isset($_GET['page']) ? $_GET['page'] : '0';
  1571. $offset = $limit * $page;
  1572. $q = $_GET['q'];
  1573. // Construct a count query if none was given.
  1574. if (!isset($count_query)) {
  1575. $count_query = preg_replace(array('/SELECT.*?FROM /As', '/ORDER BY .*/'),
  1576. array('SELECT COUNT(*) FROM ', ''), $query);
  1577. }
  1578. // We calculate the total of pages as ceil(items / limit).
  1579. $results = chado_query($count_query, $args);
  1580. if (!$results) {
  1581. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  1582. "chado_pager_query(): Query failed: %cq", array('%cq' => $count_query));
  1583. return;
  1584. }
  1585. $total_records = $results->fetchField();
  1586. // set a session variable for storing the total number of records
  1587. $GLOBALS['chado_pager'][$q][$element]['total_records'] = $total_records;
  1588. pager_default_initialize($total_records, $limit, $element);
  1589. $query .= ' LIMIT ' . (int) $limit . ' OFFSET ' . (int) $offset;
  1590. $results = chado_query($query, $args);
  1591. return $results;
  1592. }
  1593. /**
  1594. * A function to retrieve the total number of records for a pager that
  1595. * was generated using the chado_pager_query() function
  1596. *
  1597. * @param $element
  1598. * The $element argument that was passed to the chado_pager_query function
  1599. *
  1600. * @ingroup tripal_chado_query_api
  1601. */
  1602. function chado_pager_get_count($element) {
  1603. $q = $_GET['q'];
  1604. if (array_key_exists($q, $GLOBALS['chado_pager']) and
  1605. array_key_exists($element, $GLOBALS['chado_pager'][$q])) {
  1606. return $GLOBALS['chado_pager'][$q][$element]['total_records'];
  1607. }
  1608. else {
  1609. return 0;
  1610. }
  1611. }
  1612. /**
  1613. * Gets the value of a foreign key relationship
  1614. *
  1615. * This function is used by chado_select_record, chado_insert_record,
  1616. * and chado_update_record to iterate through the associate array of
  1617. * values that gets passed to each of those routines. The values array
  1618. * is nested where foreign key contraints are used to specify a value that. See
  1619. * documentation for any of those functions for further information.
  1620. *
  1621. * @param $table_desc
  1622. * A table description for the table with the foreign key relationship to be identified generated by
  1623. * hook_chado_<table name>_schema()
  1624. * @param $field
  1625. * The field in the table that is the foreign key.
  1626. * @param $values
  1627. * An associative array containing the values
  1628. * @param $options
  1629. * An associative array of additional options where the key is the option
  1630. * and the value is the value of that option. These options are passed on to chado_select_record.
  1631. *
  1632. * Additional Options Include:
  1633. * - case_insensitive_columns
  1634. * An array of columns to do a case insensitive search on.
  1635. * - regex_columns
  1636. * An array of columns where the value passed in should be treated as a regular expression
  1637. *
  1638. * @return
  1639. * A string containg the results of the foreign key lookup, or FALSE if failed.
  1640. *
  1641. * Example usage:
  1642. * @code
  1643. *
  1644. * $values = array(
  1645. * 'genus' => 'Citrus',
  1646. * 'species' => 'sinensis',
  1647. * );
  1648. * $value = chado_schema_get_foreign_key('feature', 'organism_id',$values);
  1649. *
  1650. * @endcode
  1651. * The above code selects a record from the feature table using the three fields
  1652. * that uniquely identify a feature. The $columns array simply lists the columns
  1653. * to select. The $values array is nested such that the organism is identified by
  1654. * way of the organism_id foreign key constraint by specifying the genus and
  1655. * species. The cvterm is also specified using its foreign key and the cv_id
  1656. * for the cvterm is nested as well.
  1657. *
  1658. * @ingroup tripal_chado
  1659. */
  1660. function chado_schema_get_foreign_key($table_desc, $field, $values, $options = NULL) {
  1661. // set defaults for options. If we don't set defaults then
  1662. // we get memory leaks when we try to access the elements
  1663. if (!is_array($options)) {
  1664. $options = array();
  1665. }
  1666. if (!array_key_exists('case_insensitive_columns', $options)) {
  1667. $options['case_insensitive_columns'] = array();
  1668. }
  1669. if (!array_key_exists('regex_columns', $options)) {
  1670. $options['regex_columns'] = array();
  1671. }
  1672. // get the list of foreign keys for this table description and
  1673. // iterate through those until we find the one we're looking for
  1674. $fkeys = '';
  1675. if (array_key_exists('foreign keys', $table_desc)) {
  1676. $fkeys = $table_desc['foreign keys'];
  1677. }
  1678. if ($fkeys) {
  1679. foreach ($fkeys as $name => $def) {
  1680. if (is_array($def['table'])) {
  1681. //foreign key was described 2X
  1682. $message = "The foreign key " . $name . " was defined twice. Please check modules "
  1683. . "to determine if hook_chado_schema_<version>_" . $table_desc['table'] . "() was "
  1684. . "implemented and defined this foreign key when it wasn't supposed to. Modules "
  1685. . "this hook was implemented in: " . implode(', ',
  1686. module_implements("chado_" . $table_desc['table'] . "_schema")) . ".";
  1687. tripal_report_error('tripal_chado', $message);
  1688. drupal_set_message(check_plain($message), 'error');
  1689. continue;
  1690. }
  1691. $table = $def['table'];
  1692. $columns = $def['columns'];
  1693. // iterate through the columns of the foreign key relationship
  1694. foreach ($columns as $left => $right) {
  1695. // does the left column in the relationship match our field?
  1696. if (strcmp($field, $left) == 0) {
  1697. // the column name of the foreign key matches the field we want
  1698. // so this is the right relationship. Now we want to select
  1699. $select_cols = array($right);
  1700. $result = chado_select_record($table, $select_cols, $values, $options);
  1701. $fields = array();
  1702. if ($result and count($result) > 0) {
  1703. foreach ($result as $obj) {
  1704. $fields[] = $obj->$right;
  1705. }
  1706. return $fields;
  1707. }
  1708. }
  1709. }
  1710. }
  1711. }
  1712. else {
  1713. // @todo: what do we do if we get to this point and we have a fk
  1714. // relationship expected but we don't have any definition for one in the
  1715. // table schema??
  1716. $version = $GLOBALS["chado_version"];
  1717. $message = t("There is no foreign key relationship defined for " . $field . " .
  1718. To define a foreign key relationship, determine the table this foreign
  1719. key referrs to (<foreign table>) and then implement
  1720. hook_chado_chado_schema_v<version>_<foreign table>(). See
  1721. tripal_chado_chado_v1_2_schema_feature for an example. Chado version: $version");
  1722. tripal_report_error('tripal_chado', $message);
  1723. drupal_set_message(check_plain($message), 'error');
  1724. }
  1725. return array();
  1726. }
  1727. /**
  1728. * Retrieve the name of the PostgreSQL schema housing Chado or Drupal.
  1729. *
  1730. * @param $schema
  1731. * Wehter you want the schema name for 'chado' or 'drupal'. Chado is the default.
  1732. * @return
  1733. * The name of the PostgreSQL schema housing the $schema specified.
  1734. */
  1735. function tripal_get_schema_name($schema = 'chado') {
  1736. // First we will set our default. This is what will be returned in most cases.
  1737. if ($schema == 'chado') {
  1738. $schema_name = 'chado';
  1739. }
  1740. else {
  1741. $schema_name = 'public';
  1742. }
  1743. // There are cases where modules or admin might need to change the default
  1744. // names for the schema. Thus we provide an alter hook here to allow
  1745. // the names to be changed and ensure that schema names are never hardcoded
  1746. // directly into queries.
  1747. $context = array('schema' => $schema);
  1748. drupal_alter('tripal_get_schema_name', $schema_name, $context);
  1749. return $schema_name;
  1750. }
  1751. /**
  1752. * A replacment for db_select when querying Chado.
  1753. *
  1754. * Use this function instead of db_select when querying Chado tables.
  1755. *
  1756. * @param $table
  1757. * The base table for this query. May be a string or another SelectQuery
  1758. * object. If a query object is passed, it will be used as a subselect.
  1759. * @param $alias
  1760. * The alias for the base table of this query.
  1761. * @param $options
  1762. * An array of options to control how the query operates.
  1763. *
  1764. * @return
  1765. * A new SelectQuery object for this connection.
  1766. */
  1767. function chado_db_select($table, $alias = NULL, array $options = array()) {
  1768. if (empty($options['target'])) {
  1769. $options['target'] = 'default';
  1770. }
  1771. $conninfo = Database::getConnectionInfo();
  1772. $conn = new ChadoDatabaseConnection($conninfo['default']);
  1773. return $conn->select($table, $alias, $options);
  1774. }