tripal_chado.query.api.inc 74 KB

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