tripal_chado.query.api.inc 73 KB

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