ChadoRecord.inc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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. }
  169. catch (Exception $e) {
  170. $message = t('ChadoRecord::_construct(). Could not find a record in table, !table, with the given !pkey: !record_id. ERROR: !error',
  171. ['!pkey' => $this->pkey, '!record_id' => $record_id, '!table' => $this->table_name, '!error' => $e->getMessage()]);
  172. throw new Exception($message);
  173. }
  174. }
  175. }
  176. /**
  177. * Retrieves the record ID.
  178. *
  179. * @return number
  180. */
  181. public function getID() {
  182. return $this->record_id;
  183. }
  184. /**
  185. * Retrieves the table name.
  186. *
  187. * @return string
  188. * The name of the table that the record belongs to.
  189. */
  190. public function getTable() {
  191. return $this->table_name;
  192. }
  193. /**
  194. * Retrieves the table schema.
  195. *
  196. * @return array
  197. * The Drupal schema array for the table.
  198. */
  199. public function getSchema() {
  200. return $this->schema;
  201. }
  202. /**
  203. * Performs either an update or insert into the table using the values.
  204. *
  205. * If the record already exists it will be updated. If the record does not
  206. * exist it will be inserted. This function adds a bit more overhead by
  207. * checking for the existence of the record and performing the appropriate
  208. * action. You can save time by using the insert or update functions directly
  209. * if you only need to do one of those actions specifically.
  210. *
  211. * @throws Exception
  212. */
  213. public function save() {
  214. // Determine if we need to perform an update or an insert.
  215. $num_matches = $this->find();
  216. if ($num_matches == 1) {
  217. $this->update();
  218. }
  219. if ($num_matches == 0) {
  220. $this->insert();
  221. }
  222. if ($num_matches > 1) {
  223. $message = t('ChadoRecord::save(). Could not save the record into the table, !table. '.
  224. 'Multiple records already exist that match the values: !values. '.
  225. 'Please provide a set of values that can uniquely identify a record.',
  226. ['!table' => $this->table_name, '!values' => print_r($this->values, TRUE), '!error' => $e->getMessage()]);
  227. throw new Exception($message);
  228. }
  229. }
  230. /**
  231. * Inserts the values of this object as a new record.
  232. *
  233. * @todo Support options from chado_insert_record: return_record.
  234. * @todo check for violation of unique constraint.
  235. *
  236. * @throws Exception
  237. */
  238. public function insert() {
  239. // Make sure we have values for this record before inserting.
  240. if (empty($this->values)) {
  241. $message = t('ChadoRecord::insert(). Could not insert a record into the table, !table, without any values.',
  242. ['!table' => $this->table_name]);
  243. throw new Exception($message);
  244. }
  245. // Additionally, make sure we have all the required values!
  246. if (!empty($this->missing_required_col)) {
  247. $message = t('ChadoRecord::insert(). The columns named, "!columns", require a value for the table: "!table". You can set these values using ChadoRecord::setValues().',
  248. ['!columns' => implode('", "', $this->missing_required_col), '!table' => $this->table_name]);
  249. throw new Exception($message);
  250. }
  251. // Build the SQL statement for insertion.
  252. $insert_cols = [];
  253. $insert_vals = [];
  254. $insert_args = [];
  255. foreach ($this->values as $column => $value) {
  256. $insert_cols[] = $column;
  257. $insert_vals[] = ':' . $column;
  258. $insert_args[':' . $column] = $value;
  259. }
  260. $sql = 'INSERT INTO {' . $this->table_name . '} (' .
  261. implode(", ", $insert_cols) . ') VALUES (' .
  262. implode(", ", $insert_vals) . ')';
  263. try {
  264. chado_query($sql, $insert_args);
  265. // @todo we can speed up inserts if we can find a way to not have to
  266. // run the find(), but get the newly inserted record_id directly
  267. // from the insert command.
  268. // One option may be to use the `RETURNING [pkey]` keywords in the SQL statement.
  269. $this->find();
  270. }
  271. catch (Exception $e) {
  272. $message = t('ChadoRecord::insert(). Could not insert a record into the table, !table, with the following values: !values. ERROR: !error',
  273. ['!table' => $this->table_name, '!values' => print_r($this->values, TRUE), '!error' => $e->getMessage()]);
  274. throw new Exception($message);
  275. }
  276. }
  277. /**
  278. * Updates the values of this object as a new record.
  279. *
  280. * @todo set defaults for columns not already set in values.
  281. * @todo Support options from chado_update_record: return_record.
  282. * @todo check for violation of unique constraint.
  283. * @todo if record_id not set then try finding it.
  284. *
  285. * @throws Exception
  286. */
  287. public function update() {
  288. // Make sure we have values for this record before updating.
  289. if (empty($this->values)) {
  290. $message = t('ChadoRecord::update(). Could not update a record into the table, !table, without any values.',
  291. ['!table' => $this->table_name]);
  292. throw new Exception($message);
  293. }
  294. // Additionally, make sure we have all the required values!
  295. if (!empty($this->missing_required_col)) {
  296. $message = t('ChadoRecord::update(). The columns named, "!columns", require a value for the table: "!table". You can set these values using ChadoRecord::setValues().',
  297. ['!columns' => implode('", "', $this->missing_required_col), '!table' => $this->table_name]);
  298. throw new Exception($message);
  299. }
  300. // We have to have a record ID for the record to update.
  301. if (!$this->record_id) {
  302. $message = t('ChadoRecord::update(). Could not update a record in the table, !table, without a record ID.',
  303. ['!table' => $this->table_name]);
  304. throw new Exception($message);
  305. }
  306. // Build the SQL statement for updating.
  307. $update_args = [];
  308. $sql = 'UPDATE {' . $this->table_name . '} SET ';
  309. foreach ($this->values as $column => $value) {
  310. // We're not updating the primary key so skip that if it's in the values.
  311. if ($column == $this->pkey) {
  312. continue;
  313. }
  314. $sql .= $column . ' = :' . $column . ', ';
  315. $update_args[':' . $column] = $value;
  316. }
  317. // Remove the trailing comma and space.
  318. $sql = substr($sql, 0, -2);
  319. $sql .= ' WHERE ' . $this->pkey . ' = :record_id';
  320. $update_args[':record_id'] = $this->record_id;
  321. // Now try the update.
  322. try {
  323. chado_query($sql, $update_args);
  324. }
  325. catch (Exception $e) {
  326. $message = t('ChadoRecord::update(). Could not update a record in the table, !table, with !record_id as the record ID and the following values: !values. ERROR: !error',
  327. ['!table' => $this->table_name,
  328. '!record_id' => $this->record_id,
  329. '!values' => print_r($this->values, TRUE),
  330. '!error' => $e->getMessage()]);
  331. throw new Exception($message);
  332. }
  333. }
  334. /**
  335. * Deletes the record that matches the given values.
  336. *
  337. * A record ID must be part of the current values.
  338. *
  339. * @throws Exception
  340. */
  341. public function delete() {
  342. // We have to have a record ID for the record to be deleted.
  343. if (!$this->record_id) {
  344. $message = t('ChadoRecord::delete(). Could not delete a record in the table, !table, without a record ID.',
  345. ['!table' => $this->table_name]);
  346. throw new Exception($message);
  347. }
  348. try {
  349. $sql = 'DELETE FROM {' . $this->table_name . '} WHERE ' . $this->pkey . ' = :record_id';
  350. chado_query($sql, [':record_id' => $this->record_id]);
  351. }
  352. catch (Exception $e) {
  353. $message = t('ChadoRecord::delete(). Could not delete a record in the table, !table, with !record_id as the record ID. ERROR: !error',
  354. ['!table' => $this->table_name,
  355. '!record_id' => $this->record_id,
  356. '!error' => $e->getMessage()]);
  357. throw new Exception($message);
  358. }
  359. }
  360. /**
  361. * A general-purpose setter function to set the column values for the record.
  362. *
  363. * This function should be used prior to insert or update of a record. For
  364. * an update, be sure to include the record ID in the list of values passed
  365. * to the function.
  366. *
  367. * @todo Support options from chado_insert_record: skip_validation.
  368. * @todo Validate the types match what is expected based on the schema.
  369. * @todo Set default values for columns not in this array?
  370. * @todo Support foreign key relationships: lookup the key.
  371. * @todo Support value = [a, b, c] for IN select statements?
  372. *
  373. * @param array $values
  374. * An associative array where the keys are the table column names and
  375. * the values are the record values for each column.
  376. *
  377. * @throws Exception
  378. */
  379. public function setValues($values) {
  380. // Intiailze the values array.
  381. $this->values = [];
  382. // Add the values provided into the values property.
  383. foreach ($values as $column => $value) {
  384. if (in_array($column, $this->column_names)) {
  385. $this->values[$column] = $value;
  386. }
  387. else {
  388. $message = t('ChadoRecord::setValues(). The column named, "!column", does not exist in table: "!table". Values: !values".',
  389. ['!column' => $column, '!table' => $this->table_name, '!values' => print_r($values, TRUE)]);
  390. throw new Exception($message);
  391. }
  392. }
  393. // Check whether all required columns are set and indicate using the
  394. // $required_values_set flag for faster checking in insert/update.
  395. $this->missing_required_col = [];
  396. foreach ($this->required_cols as $rcol) {
  397. // It's okay if the primary key is missing, esepecially if the user
  398. // wants to use the find() or insert() functions.
  399. if ($rcol == $this->pkey) {
  400. continue;
  401. }
  402. if (in_array($rcol, array_keys($this->values)) and $this->values[$rcol] === '__NULL__') {
  403. $this->missing_required_col[$rcol] = $rcol;
  404. }
  405. }
  406. // Check to see if the user provided the primary key (record_id).
  407. if (in_array($this->pkey, array_keys($values))) {
  408. $this->record_id = $values[$this->pkey];
  409. }
  410. // Ensure that no values are arrays.
  411. foreach ($values as $column => $value) {
  412. if (is_array($value)) {
  413. $message = t('ChadoRecord::setValues(). The column named, "!column", must be a single value but is currently: "!values". NOTE: we currently don\'t support expanding foreign key relationships or multiple values for a given column.',
  414. ['!column' => $column, '!table' => $this->table_name, '!values' => implode('", "', $value)]);
  415. throw new Exception($message);
  416. }
  417. }
  418. }
  419. /**
  420. * Returns all values for the record.
  421. *
  422. * @todo We need to follow foreign key constraints.
  423. *
  424. * @return array
  425. */
  426. public function getValues() {
  427. return $this->values;
  428. }
  429. /**
  430. * Sets the value for a specific column.
  431. *
  432. * @todo Support options from chado_insert_record: skip_validation.
  433. * @todo Validate the types match what is expected based on the schema.
  434. * @todo Set default values for columns not in this array?
  435. * @todo Support foreign key relationships: lookup the key.
  436. * @todo Support value = [a, b, c] for IN select statements?
  437. *
  438. * @param string $column_name
  439. * The name of the column to which the value should be set.
  440. * @param $value
  441. * The value to set.
  442. */
  443. public function setValue($column_name, $value) {
  444. // Make sure the column is valid.
  445. if (!in_array($column_name, $this->column_names)) {
  446. $message = t('ChadoRecord::setValue(). The column named, "!column", does not exist in table: "!table".',
  447. ['!column' => $column_name, '!table' => $this->table_name]);
  448. throw new Exception($message);
  449. }
  450. // Make sure that the value is not NULL if this is a required field.
  451. if (!in_array($column_name, $this->required_cols) and $value == '__NULL__') {
  452. $message = t('ChadoRecord::setValue(). The column named, "!column", requires a value for the table: "!table".',
  453. ['!column' => $column_name, '!table' => $this->table_name]);
  454. throw new Exception($message);
  455. }
  456. // Remove from the missing list if it was there.
  457. elseif (isset($this->missing_required_cols[$column])) {
  458. unset($this->missing_required_cols[$column]);
  459. }
  460. // Ensure that no values are arrays.
  461. if (is_array($value)) {
  462. $message = t('ChadoRecord::setValue(). The column named, "!column", must be a single value but is currently: "!values". NOTE: we currently don\'t support expanding foreign key relationships or multiple values for a given column.',
  463. ['!column' => $column, '!table' => $this->table_name, '!values' => implode('", "', $value)]);
  464. throw new Exception($message);
  465. }
  466. $this->values[$column_name] = $value;
  467. }
  468. /**
  469. * Returns the value of a specific column.
  470. *
  471. * @param string $column_name
  472. * The name of a column from the table from which to retrieve the value.
  473. */
  474. public function getValue($column_name) {
  475. // Make sure the column is valid.
  476. if (!in_array($column_name, $this->column_names)) {
  477. $message = t('ChadoRecord::getValue(). The column named, "!column", does not exist in table: "!table".',
  478. ['!column' => $column_name, '!table' => $this->table_name]);
  479. throw new Exception($message);
  480. }
  481. return $this->values[$column_name];
  482. }
  483. /**
  484. * Uses the current values given to this object to find a record.
  485. *
  486. * Use the setValues function first to set values for searching, then call
  487. * this function to find matching record. The values provided to the
  488. * setValues function must uniquely identify a record.
  489. *
  490. * @todo Support options from chado_select_record: skip_validation, has_record,
  491. * return_sql, case_insensitive_columns, regex_columns, order_by, is_duplicate,
  492. * pager, limit, offset.
  493. * @todo Support following the foreign key
  494. * @todo Support complex filtering (e.g. fmin > 50)
  495. * @todo Support multiple records being returned?
  496. *
  497. * @return
  498. * The number of matches found. If 1 is returned then the query
  499. * successfully found a match. If 0 then no matching records were found.
  500. *
  501. * @throws Exception
  502. */
  503. public function find() {
  504. // Make sure we have values for this record before searching.
  505. if (empty($this->values)) {
  506. $message = t('ChadoRecord::find(). Could not find a record from the table, !table, without any values.',
  507. ['!table' => $this->table_name]);
  508. throw new Exception($message);
  509. }
  510. // Build the SQL statement for searching.
  511. $select_args = [];
  512. $sql = 'SELECT * FROM {' . $this->table_name . '} WHERE 1=1 ';
  513. foreach ($this->values as $column => $value) {
  514. $sql .= ' AND ' . $column . ' = :' . $column;
  515. $select_args[':' . $column] = $value;
  516. }
  517. try {
  518. $results = chado_query($sql, $select_args);
  519. }
  520. catch (Exception $e) {
  521. $message = t('ChadoRecord::find(). Could not find a record in the table, !table, with the following values: !values. ERROR: !error',
  522. ['!table' => $this->table_name, '!values' => print_r($this->values, TRUE), '!error' => $e->getMessage()]);
  523. throw new Exception($message);
  524. }
  525. // If we only have a single match then we're good and we can update the
  526. // values for this object.
  527. $num_matches = $results->rowCount();
  528. if ($num_matches == 1) {
  529. $record = $results->fetchAssoc();
  530. $this->values = [];
  531. foreach ($record as $column => $value) {
  532. $this->values[$column] = $value;
  533. }
  534. $this->record_id = $record[$this->pkey];
  535. // We are no longer missing any required columns because we loaded
  536. // from the database record.
  537. $this->missing_required_col = [];
  538. }
  539. // Return the number of matches.
  540. return $num_matches;
  541. }
  542. }