tripal_chado.query.api.inc 67 KB

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