tripal_chado.query.api.inc 74 KB

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