ChadoRecord.inc 22 KB

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