ChadoRecord.inc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  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. }
  303. catch (Exception $e) {
  304. $message = t('ChadoRecord::insert(). Could not insert a record into the ' .
  305. 'table, !table, with the following values: !values. ERROR: !error',
  306. [
  307. '!table' => $this->table_name,
  308. '!values' => print_r($this->values, TRUE),
  309. '!error' => $e->getMessage(),
  310. ]);
  311. throw new Exception($message);
  312. }
  313. }
  314. /**
  315. * Updates the values of this object as a new record.
  316. *
  317. * @todo set defaults for columns not already set in values.
  318. * @todo Support options from chado_update_record: return_record.
  319. * @todo check for violation of unique constraint.
  320. * @todo if record_id not set then try finding it.
  321. *
  322. * @throws Exception
  323. */
  324. public function update() {
  325. // Make sure we have values for this record before updating.
  326. if (empty($this->values)) {
  327. $message = t('ChadoRecord::update(). Could not update a record into the ' .
  328. 'table, !table, without any values.',
  329. ['!table' => $this->table_name]);
  330. throw new Exception($message);
  331. }
  332. // Additionally, make sure we have all the required values!
  333. if (!empty($this->missing_required_col)) {
  334. $message = t('ChadoRecord::update(). The columns named, "!columns", ' .
  335. 'require a value for the table: "!table". You can set these values ' .
  336. 'using ChadoRecord::setValues(). Current values: !values.',
  337. [
  338. '!columns' => implode('", "', $this->missing_required_col),
  339. '!table' => $this->table_name,
  340. '!values' => print_r($this->values, TRUE),
  341. ]);
  342. throw new Exception($message);
  343. }
  344. // We have to have a record ID for the record to update.
  345. if (!$this->record_id) {
  346. $message = t('ChadoRecord::update(). Could not update a record in the ' .
  347. 'table, !table, without a record ID. Current values: !values.',
  348. [
  349. '!table' => $this->table_name,
  350. '!values' => print_r($this->values, TRUE),
  351. ]);
  352. throw new Exception($message);
  353. }
  354. // Build the SQL statement for updating.
  355. $update_args = [];
  356. $sql = 'UPDATE {' . $this->table_name . '} SET ';
  357. foreach ($this->values as $column => $value) {
  358. // We're not updating the primary key so skip that if it's in the values.
  359. if ($column == $this->pkey) {
  360. continue;
  361. }
  362. if ($value == '__NULL__') {
  363. $sql .= $column . ' = NULL, ';
  364. }
  365. else {
  366. $sql .= $column . ' = :' . $column . ', ';
  367. $update_args[':' . $column] = $value;
  368. }
  369. }
  370. // Remove the trailing comma and space.
  371. $sql = substr($sql, 0, -2);
  372. $sql .= ' WHERE ' . $this->pkey . ' = :record_id';
  373. $update_args[':record_id'] = $this->record_id;
  374. // Now try the update.
  375. try {
  376. chado_query($sql, $update_args);
  377. }
  378. catch (Exception $e) {
  379. $message = t('ChadoRecord::update(). Could not update a record in the ' .
  380. 'table, !table, with !record_id as the record ID and the following ' .
  381. 'values: !values. ERROR: !error',
  382. [
  383. '!table' => $this->table_name,
  384. '!record_id' => $this->record_id,
  385. '!values' => print_r($this->values, TRUE),
  386. '!error' => $e->getMessage(),
  387. ]);
  388. throw new Exception($message);
  389. }
  390. }
  391. /**
  392. * Deletes the record that matches the given values.
  393. *
  394. * A record ID must be part of the current values.
  395. *
  396. * @throws Exception
  397. */
  398. public function delete() {
  399. // We have to have a record ID for the record to be deleted.
  400. if (!$this->record_id) {
  401. $message = t('ChadoRecord::delete(). Could not delete a record in the table, !table, without a record ID.',
  402. ['!table' => $this->table_name]);
  403. throw new Exception($message);
  404. }
  405. try {
  406. $sql = 'DELETE FROM {' . $this->table_name . '} WHERE ' . $this->pkey . ' = :record_id';
  407. chado_query($sql, [':record_id' => $this->record_id]);
  408. } catch (Exception $e) {
  409. $message = t('ChadoRecord::delete(). Could not delete a record in the table, !table, with !record_id as the record ID. ERROR: !error',
  410. [
  411. '!table' => $this->table_name,
  412. '!record_id' => $this->record_id,
  413. '!error' => $e->getMessage(),
  414. ]);
  415. throw new Exception($message);
  416. }
  417. }
  418. /**
  419. * A general-purpose setter function to set the column values for the record.
  420. *
  421. * This function should be used prior to insert or update of a record. For
  422. * an update, be sure to include the record ID in the list of values passed
  423. * to the function.
  424. *
  425. * @todo Support options from chado_insert_record: skip_validation.
  426. * @todo Validate the types match what is expected based on the schema.
  427. * @todo Set default values for columns not in this array?
  428. * @todo Support foreign key relationships: lookup the key.
  429. * @todo Support value = [a, b, c] for IN select statements?
  430. *
  431. * @param array $values
  432. * An associative array where the keys are the table column names and
  433. * the values are the record values for each column.
  434. *
  435. * @throws Exception
  436. */
  437. public function setValues($values) {
  438. // Intiailze the values array.
  439. $this->values = [];
  440. // Add the values provided into the values property.
  441. foreach ($values as $column => $value) {
  442. if (in_array($column, $this->column_names)) {
  443. $this->values[$column] = $value;
  444. }
  445. else {
  446. $message = t('ChadoRecord::setValues(). The column named, "!column", ' .
  447. 'does not exist in table: "!table". Values: !values".',
  448. [
  449. '!column' => $column,
  450. '!table' => $this->table_name,
  451. '!values' => print_r($values, TRUE),
  452. ]);
  453. throw new Exception($message);
  454. }
  455. }
  456. // Check whether all required columns are set and indicate using the
  457. // $required_values_set flag for faster checking in insert/update.
  458. $this->missing_required_col = [];
  459. foreach ($this->required_cols as $rcol) {
  460. // It's okay if the primary key is missing, esepecially if the user
  461. // wants to use the find() or insert() functions.
  462. if ($rcol == $this->pkey) {
  463. continue;
  464. }
  465. if (in_array($rcol, array_keys($this->values)) and $this->values[$rcol] === '__NULL__') {
  466. $this->missing_required_col[$rcol] = TRUE;
  467. }
  468. }
  469. // Check to see if the user provided the primary key (record_id).
  470. if (in_array($this->pkey, array_keys($values))) {
  471. $this->record_id = $values[$this->pkey];
  472. }
  473. // Ensure that no values are arrays.
  474. foreach ($values as $column => $value) {
  475. if (is_array($value)) {
  476. $message = t('ChadoRecord::setValues(). The column named, "!column", ' .
  477. 'must be a single value but is currently: "!values". NOTE: this function ' .
  478. 'currently does not support expanding foreign key relationships or ' .
  479. 'multiple values for a given column.',
  480. [
  481. '!column' => $column,
  482. '!table' => $this->table_name,
  483. '!values' => implode('", "', $value),
  484. ]);
  485. throw new Exception($message);
  486. }
  487. }
  488. }
  489. /**
  490. * Returns all values for the record.
  491. *
  492. * @todo We need to follow foreign key constraints.
  493. *
  494. * @return array
  495. */
  496. public function getValues() {
  497. return $this->values;
  498. }
  499. /**
  500. * Sets the value for a specific column.
  501. *
  502. * @todo Support options from chado_insert_record: skip_validation.
  503. * @todo Validate the types match what is expected based on the schema.
  504. * @todo Set default values for columns not in this array?
  505. * @todo Support foreign key relationships: lookup the key.
  506. * @todo Support value = [a, b, c] for IN select statements?
  507. *
  508. * @param string $column_name
  509. * The name of the column to which the value should be set.
  510. * @param $value
  511. * The value to set.
  512. */
  513. public function setValue($column_name, $value) {
  514. // Make sure the column is valid.
  515. if (!in_array($column_name, $this->column_names)) {
  516. $message = t('ChadoRecord::setValue(). The column named, "!column", does ' .
  517. 'not exist in table: "!table".',
  518. [
  519. '!column' => $column_name,
  520. '!table' => $this->table_name,
  521. ]);
  522. throw new Exception($message);
  523. }
  524. // Make sure that the value is not NULL if this is a required field.
  525. if (in_array($column_name, $this->required_cols) and $value == '__NULL__') {
  526. $message = t('ChadoRecord::setValue(). The column named, "!column", ' .
  527. 'requires a value for the table: "!table".',
  528. [
  529. '!column' => $column_name,
  530. '!table' => $this->table_name,
  531. ]);
  532. throw new Exception($message);
  533. }
  534. // Remove from the missing list if it was there.
  535. if (isset($this->missing_required_col[$column_name])) {
  536. unset($this->missing_required_col[$column_name]);
  537. }
  538. // Ensure that no values are arrays.
  539. if (is_array($value)) {
  540. $message = t('ChadoRecord::setValue(). The column named, "!column", ' .
  541. 'must be a single value but is currently: "!values". NOTE: this function ' .
  542. 'currently does not support expanding foreign key relationships or ' .
  543. 'multiple values for a given column.',
  544. [
  545. '!column' => $column,
  546. '!table' => $this->table_name,
  547. '!values' => implode('", "', $value),
  548. ]);
  549. throw new Exception($message);
  550. }
  551. $this->values[$column_name] = $value;
  552. }
  553. /**
  554. * Returns the value of a specific column.
  555. *
  556. * @param string $column_name
  557. * The name of a column from the table from which to retrieve the value.
  558. */
  559. public function getValue($column_name) {
  560. // Make sure the column is valid.
  561. if (!in_array($column_name, $this->column_names)) {
  562. $message = t('ChadoRecord::getValue(). The column named, "!column", ' .
  563. 'does not exist in table: "!table".',
  564. [
  565. '!column' => $column_name,
  566. '!table' => $this->table_name,
  567. ]);
  568. throw new Exception($message);
  569. }
  570. return $this->values[$column_name];
  571. }
  572. /**
  573. * Uses the current values given to this object to find a record.
  574. *
  575. * Use the setValues function first to set values for searching, then call
  576. * this function to find matching record. The values provided to the
  577. * setValues function must uniquely identify a record.
  578. *
  579. * @todo Support options from chado_select_record: skip_validation,
  580. * has_record, return_sql, case_insensitive_columns, regex_columns,
  581. * order_by, is_duplicate, pager, limit, offset.
  582. * @todo Support following the foreign key
  583. * @todo Support complex filtering (e.g. fmin > 50)
  584. * @todo Support multiple records being returned?
  585. *
  586. * @return
  587. * The number of matches found. If 1 is returned then the query
  588. * successfully found a match. If 0 then no matching records were found.
  589. *
  590. * @throws Exception
  591. */
  592. public function find() {
  593. // Make sure we have values for this record before searching.
  594. if (empty($this->values)) {
  595. $message = t('ChadoRecord::find(). Could not find a record from ' .
  596. 'the table, !table, without any values.',
  597. ['!table' => $this->table_name]);
  598. throw new Exception($message);
  599. }
  600. // Build the SQL statement for searching.
  601. $select_args = [];
  602. $sql = 'SELECT * FROM {' . $this->table_name . '} WHERE 1=1 ';
  603. foreach ($this->values as $column => $value) {
  604. $sql .= ' AND ' . $column . ' = :' . $column;
  605. $select_args[':' . $column] = $value;
  606. }
  607. try {
  608. $results = chado_query($sql, $select_args);
  609. }
  610. catch (Exception $e) {
  611. $message = t('ChadoRecord::find(). Could not find a record in the ' .
  612. 'table, !table, with the following values: !values. ERROR: !error',
  613. [
  614. '!table' => $this->table_name,
  615. '!values' => print_r($this->values, TRUE),
  616. '!error' => $e->getMessage(),
  617. ]);
  618. throw new Exception($message);
  619. }
  620. // If we only have a single match then we're good and we can update the
  621. // values for this object.
  622. $num_matches = $results->rowCount();
  623. if ($num_matches == 1) {
  624. $record = $results->fetchAssoc();
  625. $this->values = [];
  626. foreach ($record as $column => $value) {
  627. $this->values[$column] = $value;
  628. }
  629. $this->record_id = $record[$this->pkey];
  630. // We are no longer missing any required columns because we loaded
  631. // from the database record.
  632. $this->missing_required_col = [];
  633. }
  634. // Return the number of matches.
  635. return $num_matches;
  636. }
  637. }