tripal_chado.query.api.inc 66 KB

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