ChadoRecord.inc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. <?php
  2. /**
  3. * Provide a class for basic querying of Chado.
  4. *
  5. * Specifically tihs class provides select, insert, update and delete.
  6. *
  7. * Eventually this class is meants to replace the existing
  8. * chado_select_record(), chado_insert_record(), chado_update_record() and
  9. * chado_delete_record() API functions to create a cleaner, more maintainable
  10. * and more easily tested interface to querying Chado.
  11. *
  12. * @todo Add documentation for save() and delete().
  13. *
  14. * Basic Usage:
  15. * - Select/Find
  16. * The following example selects an organism with the scientific name
  17. * "Tripalus databasica" from the organism table of Chado.
  18. * @code
  19. // First we create an instance of the ChadoRecord class
  20. // specifying the table we want to query.
  21. $record = new \ChadoRecord('organism');
  22. // Next we indicate the values we know.
  23. $record->setValues([
  24. 'genus' => 'Tripalus',
  25. 'species' => 'databasica',
  26. ]);
  27. // And finally we simply ask the class to find the chado record
  28. // we indicated when we set the values above.
  29. $success = $record->find();
  30. if ($success) {
  31. // Retrieve the values if we were successful in finding the record.
  32. $result = $record->getValues();
  33. }
  34. * @endcode
  35. * - Insert:
  36. * The following example inserts a sample record into the stock table.
  37. * @code
  38. // First we create an instance of the ChadoRecord class
  39. // specifying the table we want to query.
  40. $record = new \ChadoRecord('stock');
  41. // Next we indicate the values we know.
  42. $record->setValues([
  43. 'name' => 'My Favourite Plant',
  44. 'uniquename' => 'Plectranthus scutellarioides Trailing Plum Brocade',
  45. 'organism_id' => [ 'genus' => 'Tripalus', 'species' => 'databasica' ],
  46. 'type_id' => [ 'name' => 'sample', 'cv_id' => [ 'name' => 'Sample processing and separation techniques' ] ],
  47. ]);
  48. // And finally, we ask the class to insert the chado record
  49. // we described when we set the values above.
  50. $result = $record->insert();
  51. * @endcode
  52. * - Update:
  53. * The following example updates the "Tripalus databasica" record to specify the common name.
  54. * @code
  55. // For brevity we're going to hardcode the original record
  56. // including the id although you would Never do this in practice.
  57. // Rather you would first find the record as shown in a previous example.
  58. $original_record = [
  59. 'organism_id' => 1,
  60. 'genus' => 'Tripalus',
  61. 'species' => 'databasica',
  62. ];
  63. // First we create an instance of the ChadoRecord class
  64. // specifying the table we want to query.
  65. // NOTICE: this time we set the record_id when creating the instance.
  66. $record = new \ChadoRecord('organism', $original_record['organism_id']);
  67. // Now we set the values we want to change.
  68. $record->setValues([
  69. 'common_name' => 'Tripal',
  70. ]);
  71. // And then tell the class to update the record.
  72. $record->update();
  73. * @endcode
  74. */
  75. class ChadoRecord {
  76. /**
  77. * @var string
  78. * Holds the name of the table that this record belogns to.
  79. */
  80. protected $table_name = '';
  81. /**
  82. * @var array
  83. * Holds the Drupal schema definition for this table.
  84. */
  85. protected $schema = [];
  86. /**
  87. * @var array
  88. * Holds the values for the columns of the record
  89. */
  90. protected $values = [];
  91. /**
  92. * @var array
  93. * An array of required columns.
  94. */
  95. protected $required_cols = [];
  96. /**
  97. * @var boolean
  98. * An array of required columns which have yet to be set.
  99. */
  100. protected $missing_required_col = [];
  101. /**
  102. * @var integer
  103. * The numeric Id for this record.
  104. */
  105. protected $record_id = NULL;
  106. /**
  107. * @var string
  108. * The column name for the primary key.
  109. */
  110. protected $pkey = '';
  111. /**
  112. * The list of column names in the table.
  113. * @var array
  114. */
  115. protected $column_names = [];
  116. /**
  117. * The ChadoRecord constructor
  118. *
  119. * @param string $table_name
  120. * The name of the table that the record belongs to.
  121. *
  122. * @param string $record_id
  123. * An optional record ID if this record is already present in Chado.
  124. */
  125. public function __construct($table_name, $record_id = NULL) {
  126. if (!$table_name) {
  127. $message = t('ChadoRecord::_construct(). The $table_name argument is required for a ChadoRecord instance.');
  128. throw new Exception($message);
  129. }
  130. // Set the table name and schema.
  131. $this->table_name = $table_name;
  132. $this->schema = chado_get_schema($this->table_name);
  133. if (!$this->schema) {
  134. $message = t('ChadoRecord::_construct(). Could not find a matching table schema in Chado for the table: !table.',
  135. ['!table' => $this->table_name]);
  136. throw new Exception($message);
  137. }
  138. // Chado tables never have more than one column as a primary key so
  139. // we are good just getting the first element.
  140. $this->pkey = $this->schema['primary key'][0];
  141. // Save the column names.
  142. foreach ($this->schema['fields'] as $column_name => $col_details) {
  143. $this->column_names[] = $column_name;
  144. }
  145. // Get the required columns.
  146. foreach ($this->schema['fields'] as $column => $col_schema) {
  147. foreach ($col_schema as $param => $val) {
  148. if (preg_match('/not null/i', $param) and $col_schema[$param]) {
  149. $this->required_cols[] = $column;
  150. }
  151. }
  152. }
  153. // Currently all required columns are missing.
  154. $this->missing_required_col = $this->required_cols;
  155. // If a record_id was provided then lookup the record and set the values.
  156. if ($record_id) {
  157. try {
  158. $sql = 'SELECT * FROM {' . $this->table_name . '} WHERE ' . $this->pkey . ' = :record_id';
  159. $result = chado_query($sql, [':record_id' => $record_id]);
  160. $values = $result->fetchAssoc();
  161. if (empty($values)) {
  162. $message = t('ChadoRecord::_construct(). Could not find a record in table, !table, with the given !pkey: !record_id.',
  163. ['!pkey' => $this->pkey, '!record_id' => $record_id, '!table' => $this->table_name]);
  164. throw new Exception($message);
  165. }
  166. $this->record_id = $record_id;
  167. $this->values = $values;
  168. $this->missing_required_col = [];
  169. }
  170. catch (Exception $e) {
  171. $message = t('ChadoRecord::_construct(). Could not find a record in table, !table, with the given !pkey: !record_id. ERROR: !error',
  172. ['!pkey' => $this->pkey, '!record_id' => $record_id, '!table' => $this->table_name, '!error' => $e->getMessage()]);
  173. throw new Exception($message);
  174. }
  175. }
  176. }
  177. /**
  178. * Retrieves the record ID.
  179. *
  180. * @return number
  181. */
  182. public function getID() {
  183. return $this->record_id;
  184. }
  185. /**
  186. * Retrieves the table name.
  187. *
  188. * @return string
  189. * The name of the table that the record belongs to.
  190. */
  191. public function getTable() {
  192. return $this->table_name;
  193. }
  194. /**
  195. * Retrieves the table schema.
  196. *
  197. * @return array
  198. * The Drupal schema array for the table.
  199. */
  200. public function getSchema() {
  201. return $this->schema;
  202. }
  203. /**
  204. * Performs either an update or insert into the table using the values.
  205. *
  206. * If the record already exists it will be updated. If the record does not
  207. * exist it will be inserted. This function adds a bit more overhead by
  208. * checking for the existence of the record and performing the appropriate
  209. * action. You can save time by using the insert or update functions directly
  210. * if you only need to do one of those actions specifically.
  211. *
  212. * @throws Exception
  213. */
  214. public function save() {
  215. // Determine if we need to perform an update or an insert.
  216. $num_matches = $this->find();
  217. if ($num_matches == 1) {
  218. $this->update();
  219. }
  220. if ($num_matches == 0) {
  221. $this->insert();
  222. }
  223. if ($num_matches > 1) {
  224. $message = t('ChadoRecord::save(). Could not save the record into the table, !table. '.
  225. 'Multiple records already exist that match the values: !values. '.
  226. 'Please provide a set of values that can uniquely identify a record.',
  227. ['!table' => $this->table_name, '!values' => print_r($this->values, TRUE), '!error' => $e->getMessage()]);
  228. throw new Exception($message);
  229. }
  230. }
  231. /**
  232. * Inserts the values of this object as a new record.
  233. *
  234. * @todo Support options from chado_insert_record: return_record.
  235. * @todo check for violation of unique constraint.
  236. *
  237. * @throws Exception
  238. */
  239. public function insert() {
  240. // Make sure we have values for this record before inserting.
  241. if (empty($this->values)) {
  242. $message = t('ChadoRecord::insert(). Could not insert a record into the table, !table, without any values.',
  243. ['!table' => $this->table_name]);
  244. throw new Exception($message);
  245. }
  246. // Additionally, make sure we have all the required values!
  247. if (!empty($this->missing_required_col)) {
  248. $message = t('ChadoRecord::insert(). The columns named, "!columns", ' .
  249. 'require a value for the table: "!table". You can set these values ' .
  250. 'using ChadoRecord::setValues(). Current values: !values.',
  251. ['!columns' => implode('", "', $this->missing_required_col),
  252. '!table' => $this->table_name,
  253. '!values' => print_r($this->values, TRUE)]);
  254. throw new Exception($message);
  255. }
  256. // Build the SQL statement for insertion.
  257. $insert_cols = [];
  258. $insert_vals = [];
  259. $insert_args = [];
  260. foreach ($this->values as $column => $value) {
  261. $insert_cols[] = $column;
  262. $insert_vals[] = ':' . $column;
  263. $insert_args[':' . $column] = $value;
  264. }
  265. $sql = 'INSERT INTO {' . $this->table_name . '} (' .
  266. implode(", ", $insert_cols) . ') VALUES (' .
  267. implode(", ", $insert_vals) . ')';
  268. if ($this->pkey) {
  269. $sql .= ' RETURNING ' . $this->pkey;
  270. }
  271. try {
  272. $result = chado_query($sql, $insert_args);
  273. if ($this->pkey) {
  274. $this->values[$this->pkey] = $result->fetchField();
  275. }
  276. }
  277. catch (Exception $e) {
  278. $message = t('ChadoRecord::insert(). Could not insert a record into the ' .
  279. 'table, !table, with the following values: !values. ERROR: !error',
  280. ['!table' => $this->table_name,
  281. '!values' => print_r($this->values, TRUE),
  282. '!error' => $e->getMessage()]);
  283. throw new Exception($message);
  284. }
  285. }
  286. /**
  287. * Updates the values of this object as a new record.
  288. *
  289. * @todo set defaults for columns not already set in values.
  290. * @todo Support options from chado_update_record: return_record.
  291. * @todo check for violation of unique constraint.
  292. * @todo if record_id not set then try finding it.
  293. *
  294. * @throws Exception
  295. */
  296. public function update() {
  297. // Make sure we have values for this record before updating.
  298. if (empty($this->values)) {
  299. $message = t('ChadoRecord::update(). Could not update a record into the ' .
  300. 'table, !table, without any values.',
  301. ['!table' => $this->table_name]);
  302. throw new Exception($message);
  303. }
  304. // Additionally, make sure we have all the required values!
  305. if (!empty($this->missing_required_col)) {
  306. $message = t('ChadoRecord::update(). The columns named, "!columns", ' .
  307. 'require a value for the table: "!table". You can set these values ' .
  308. 'using ChadoRecord::setValues(). Current values: !values.',
  309. ['!columns' => implode('", "', $this->missing_required_col),
  310. '!table' => $this->table_name,
  311. '!values' => print_r($this->values, TRUE)]);
  312. throw new Exception($message);
  313. }
  314. // We have to have a record ID for the record to update.
  315. if (!$this->record_id) {
  316. $message = t('ChadoRecord::update(). Could not update a record in the ' .
  317. 'table, !table, without a record ID. Current values: !values.',
  318. ['!table' => $this->table_name,
  319. '!values' => print_r($this->values, TRUE)]);
  320. throw new Exception($message);
  321. }
  322. // Build the SQL statement for updating.
  323. $update_args = [];
  324. $sql = 'UPDATE {' . $this->table_name . '} SET ';
  325. foreach ($this->values as $column => $value) {
  326. // We're not updating the primary key so skip that if it's in the values.
  327. if ($column == $this->pkey) {
  328. continue;
  329. }
  330. $sql .= $column . ' = :' . $column . ', ';
  331. $update_args[':' . $column] = $value;
  332. }
  333. // Remove the trailing comma and space.
  334. $sql = substr($sql, 0, -2);
  335. $sql .= ' WHERE ' . $this->pkey . ' = :record_id';
  336. $update_args[':record_id'] = $this->record_id;
  337. // Now try the update.
  338. try {
  339. chado_query($sql, $update_args);
  340. }
  341. catch (Exception $e) {
  342. $message = t('ChadoRecord::update(). Could not update a record in the ' .
  343. 'table, !table, with !record_id as the record ID and the following ' .
  344. 'values: !values. ERROR: !error',
  345. ['!table' => $this->table_name,
  346. '!record_id' => $this->record_id,
  347. '!values' => print_r($this->values, TRUE),
  348. '!error' => $e->getMessage()]);
  349. throw new Exception($message);
  350. }
  351. }
  352. /**
  353. * Deletes the record that matches the given values.
  354. *
  355. * A record ID must be part of the current values.
  356. *
  357. * @throws Exception
  358. */
  359. public function delete() {
  360. // We have to have a record ID for the record to be deleted.
  361. if (!$this->record_id) {
  362. $message = t('ChadoRecord::delete(). Could not delete a record in the table, !table, without a record ID.',
  363. ['!table' => $this->table_name]);
  364. throw new Exception($message);
  365. }
  366. try {
  367. $sql = 'DELETE FROM {' . $this->table_name . '} WHERE ' . $this->pkey . ' = :record_id';
  368. chado_query($sql, [':record_id' => $this->record_id]);
  369. }
  370. catch (Exception $e) {
  371. $message = t('ChadoRecord::delete(). Could not delete a record in the table, !table, with !record_id as the record ID. ERROR: !error',
  372. ['!table' => $this->table_name,
  373. '!record_id' => $this->record_id,
  374. '!error' => $e->getMessage()]);
  375. throw new Exception($message);
  376. }
  377. }
  378. /**
  379. * A general-purpose setter function to set the column values for the record.
  380. *
  381. * This function should be used prior to insert or update of a record. For
  382. * an update, be sure to include the record ID in the list of values passed
  383. * to the function.
  384. *
  385. * @todo Support options from chado_insert_record: skip_validation.
  386. * @todo Validate the types match what is expected based on the schema.
  387. * @todo Set default values for columns not in this array?
  388. * @todo Support foreign key relationships: lookup the key.
  389. * @todo Support value = [a, b, c] for IN select statements?
  390. *
  391. * @param array $values
  392. * An associative array where the keys are the table column names and
  393. * the values are the record values for each column.
  394. *
  395. * @throws Exception
  396. */
  397. public function setValues($values) {
  398. // Intiailze the values array.
  399. $this->values = [];
  400. // Add the values provided into the values property.
  401. foreach ($values as $column => $value) {
  402. if (in_array($column, $this->column_names)) {
  403. $this->values[$column] = $value;
  404. }
  405. else {
  406. $message = t('ChadoRecord::setValues(). The column named, "!column", ' .
  407. 'does not exist in table: "!table". Values: !values".',
  408. ['!column' => $column,
  409. '!table' => $this->table_name,
  410. '!values' => print_r($values, TRUE)]);
  411. throw new Exception($message);
  412. }
  413. }
  414. // Check whether all required columns are set and indicate using the
  415. // $required_values_set flag for faster checking in insert/update.
  416. $this->missing_required_col = [];
  417. foreach ($this->required_cols as $rcol) {
  418. // It's okay if the primary key is missing, esepecially if the user
  419. // wants to use the find() or insert() functions.
  420. if ($rcol == $this->pkey) {
  421. continue;
  422. }
  423. if (in_array($rcol, array_keys($this->values)) and $this->values[$rcol] === '__NULL__') {
  424. $this->missing_required_col[$rcol] = $rcol;
  425. }
  426. }
  427. // Check to see if the user provided the primary key (record_id).
  428. if (in_array($this->pkey, array_keys($values))) {
  429. $this->record_id = $values[$this->pkey];
  430. }
  431. // Ensure that no values are arrays.
  432. foreach ($values as $column => $value) {
  433. if (is_array($value)) {
  434. $message = t('ChadoRecord::setValues(). The column named, "!column", ' .
  435. 'must be a single value but is currently: "!values". NOTE: this function ' .
  436. 'currently does not support expanding foreign key relationships or ' .
  437. 'multiple values for a given column.',
  438. ['!column' => $column,
  439. '!table' => $this->table_name,
  440. '!values' => implode('", "', $value)]);
  441. throw new Exception($message);
  442. }
  443. }
  444. }
  445. /**
  446. * Returns all values for the record.
  447. *
  448. * @todo We need to follow foreign key constraints.
  449. *
  450. * @return array
  451. */
  452. public function getValues() {
  453. return $this->values;
  454. }
  455. /**
  456. * Sets the value for a specific column.
  457. *
  458. * @todo Support options from chado_insert_record: skip_validation.
  459. * @todo Validate the types match what is expected based on the schema.
  460. * @todo Set default values for columns not in this array?
  461. * @todo Support foreign key relationships: lookup the key.
  462. * @todo Support value = [a, b, c] for IN select statements?
  463. *
  464. * @param string $column_name
  465. * The name of the column to which the value should be set.
  466. * @param $value
  467. * The value to set.
  468. */
  469. public function setValue($column_name, $value) {
  470. // Make sure the column is valid.
  471. if (!in_array($column_name, $this->column_names)) {
  472. $message = t('ChadoRecord::setValue(). The column named, "!column", does ' .
  473. 'not exist in table: "!table".',
  474. ['!column' => $column_name,
  475. '!table' => $this->table_name]);
  476. throw new Exception($message);
  477. }
  478. // Make sure that the value is not NULL if this is a required field.
  479. if (!in_array($column_name, $this->required_cols) and $value == '__NULL__') {
  480. $message = t('ChadoRecord::setValue(). The column named, "!column", ' .
  481. 'requires a value for the table: "!table".',
  482. ['!column' => $column_name,
  483. '!table' => $this->table_name]);
  484. throw new Exception($message);
  485. }
  486. // Remove from the missing list if it was there.
  487. elseif (isset($this->missing_required_cols[$column])) {
  488. unset($this->missing_required_cols[$column]);
  489. }
  490. // Ensure that no values are arrays.
  491. if (is_array($value)) {
  492. $message = t('ChadoRecord::setValue(). The column named, "!column", ' .
  493. 'must be a single value but is currently: "!values". NOTE: this function ' .
  494. 'currently does not support expanding foreign key relationships or ' .
  495. 'multiple values for a given column.',
  496. ['!column' => $column,
  497. '!table' => $this->table_name,
  498. '!values' => implode('", "', $value)]);
  499. throw new Exception($message);
  500. }
  501. $this->values[$column_name] = $value;
  502. }
  503. /**
  504. * Returns the value of a specific column.
  505. *
  506. * @param string $column_name
  507. * The name of a column from the table from which to retrieve the value.
  508. */
  509. public function getValue($column_name) {
  510. // Make sure the column is valid.
  511. if (!in_array($column_name, $this->column_names)) {
  512. $message = t('ChadoRecord::getValue(). The column named, "!column", ' .
  513. 'does not exist in table: "!table".',
  514. ['!column' => $column_name,
  515. '!table' => $this->table_name]);
  516. throw new Exception($message);
  517. }
  518. return $this->values[$column_name];
  519. }
  520. /**
  521. * Uses the current values given to this object to find a record.
  522. *
  523. * Use the setValues function first to set values for searching, then call
  524. * this function to find matching record. The values provided to the
  525. * setValues function must uniquely identify a record.
  526. *
  527. * @todo Support options from chado_select_record: skip_validation, has_record,
  528. * return_sql, case_insensitive_columns, regex_columns, order_by, is_duplicate,
  529. * pager, limit, offset.
  530. * @todo Support following the foreign key
  531. * @todo Support complex filtering (e.g. fmin > 50)
  532. * @todo Support multiple records being returned?
  533. *
  534. * @return
  535. * The number of matches found. If 1 is returned then the query
  536. * successfully found a match. If 0 then no matching records were found.
  537. *
  538. * @throws Exception
  539. */
  540. public function find() {
  541. // Make sure we have values for this record before searching.
  542. if (empty($this->values)) {
  543. $message = t('ChadoRecord::find(). Could not find a record from ' .
  544. 'the table, !table, without any values.',
  545. ['!table' => $this->table_name]);
  546. throw new Exception($message);
  547. }
  548. // Build the SQL statement for searching.
  549. $select_args = [];
  550. $sql = 'SELECT * FROM {' . $this->table_name . '} WHERE 1=1 ';
  551. foreach ($this->values as $column => $value) {
  552. $sql .= ' AND ' . $column . ' = :' . $column;
  553. $select_args[':' . $column] = $value;
  554. }
  555. try {
  556. $results = chado_query($sql, $select_args);
  557. }
  558. catch (Exception $e) {
  559. $message = t('ChadoRecord::find(). Could not find a record in the ' .
  560. 'table, !table, with the following values: !values. ERROR: !error',
  561. ['!table' => $this->table_name,
  562. '!values' => print_r($this->values, TRUE),
  563. '!error' => $e->getMessage()]);
  564. throw new Exception($message);
  565. }
  566. // If we only have a single match then we're good and we can update the
  567. // values for this object.
  568. $num_matches = $results->rowCount();
  569. if ($num_matches == 1) {
  570. $record = $results->fetchAssoc();
  571. $this->values = [];
  572. foreach ($record as $column => $value) {
  573. $this->values[$column] = $value;
  574. }
  575. $this->record_id = $record[$this->pkey];
  576. // We are no longer missing any required columns because we loaded
  577. // from the database record.
  578. $this->missing_required_col = [];
  579. }
  580. // Return the number of matches.
  581. return $num_matches;
  582. }
  583. }