ChadoRecord.inc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. <?php
  2. class ChadoRecord {
  3. /**
  4. * @var string
  5. * Holds the name of the table that this record belogns to.
  6. */
  7. protected $table_name = '';
  8. /**
  9. * @var array
  10. * Holds the Drupal schema definition for this table.
  11. */
  12. protected $schema = [];
  13. /**
  14. * @var array
  15. * Holds the values for the columns of the record
  16. */
  17. protected $values = [];
  18. /**
  19. * @var array
  20. * An array of required columns.
  21. */
  22. protected $required_cols = [];
  23. /**
  24. * @var integer
  25. * The numeric Id for this record.
  26. */
  27. protected $record_id = NULL;
  28. /**
  29. * @var string
  30. * The column name for the primary key.
  31. */
  32. protected $pkey = '';
  33. /**
  34. * The list of column names in the table.
  35. * @var array
  36. */
  37. protected $column_names = [];
  38. /**
  39. * The ChadoRecord constructor
  40. *
  41. * @param string $table_name
  42. * The name of the table that the record belongs to.
  43. *
  44. * @param string $record_id
  45. * An optional record ID if this record is already present in Chado.
  46. */
  47. public function __construct($table_name, $record_id = NULL) {
  48. if (!$table_name) {
  49. $message = t('ChadoRecord::_construct(). The $table_name argument is required for a ChadoRecord instance.');
  50. throw new Exception($message);
  51. }
  52. // Set the table name and schema.
  53. $this->table_name = $table_name;
  54. $this->schema = chado_get_schema($this->table_name);
  55. if (!$this->schema) {
  56. $message = t('ChadoRecord::_construct(). Could not find a matching table schema in Chado for the table: !table.',
  57. ['!table' => $this->table_name]);
  58. throw new Exception($message);
  59. }
  60. // Chado tables never have more than one column as a primary key so
  61. // we are good just getting the first element.
  62. $this->pkey = $this->schema['primary key'][0];
  63. // Save the column names.
  64. foreach ($this->schema['fields'] as $column_name => $col_details) {
  65. $this->column_names[] = $column_name;
  66. }
  67. // Get the required columns.
  68. foreach ($this->schema['fields'] as $column => $col_schema) {
  69. foreach ($col_schema as $param => $val) {
  70. if (preg_match('/not null/i', $param) and $col_schema[$param]) {
  71. $this->required_cols[] = $column;
  72. }
  73. }
  74. }
  75. // If a record_id was provided then lookup the record and set the values.
  76. if ($record_id) {
  77. try {
  78. $sql = 'SELECT * FROM {' . $this->table_name . '} WHERE ' . $this->pkey . ' = :record_id';
  79. $result = chado_query($sql, [':record_id' => $record_id]);
  80. $values = $result->fetchAssoc();
  81. if (empty($values)) {
  82. $message = t('ChadoRecord::_construct(). Could not find a record in table, !table, with the given !pkey: !record_id.',
  83. ['!pkey' => $this->pkey, '!record_id' => $record_id, '!table' => $this->table_name]);
  84. throw new Exception($message);
  85. }
  86. $this->record_id = $record_id;
  87. $this->values = $values;
  88. }
  89. catch (Exception $e) {
  90. $message = t('ChadoRecord::_construct(). Could not find a record in table, !table, with the given !pkey: !record_id. ERROR: !error',
  91. ['!pkey' => $this->pkey, '!record_id' => $record_id, '!table' => $this->table_name, '!error' => $e->getMessage()]);
  92. throw new Exception($message);
  93. }
  94. }
  95. }
  96. /**
  97. * Retrieves the record ID.
  98. *
  99. * @return number
  100. */
  101. public function getID() {
  102. return $this->record_id;
  103. }
  104. /**
  105. * Retrieves the table name.
  106. *
  107. * @return string
  108. * The name of the table that the record belongs to.
  109. */
  110. public function getTable() {
  111. return $this->table_name;
  112. }
  113. /**
  114. * Retrieves the table schema.
  115. *
  116. * @return array
  117. * The Drupal schema array for the table.
  118. */
  119. public function getSchema() {
  120. return $this->schema;
  121. }
  122. /**
  123. * Performs either an update or insert into the table using the values.
  124. *
  125. * If the record already exists it will be updated. If the record does not
  126. * exist it will be inserted. This function adds a bit more overhead by
  127. * checking for the existence of the record and performing the appropriate
  128. * action. You can save time by using the insert or update functions directly
  129. * if you only need to do one of those actions specifically.
  130. *
  131. * @throws Exception
  132. */
  133. public function save() {
  134. // Determine if we need to perform an update or an insert.
  135. $num_matches = $this->find();
  136. if ($num_matches == 1) {
  137. $this->update();
  138. }
  139. if ($num_matches == 0) {
  140. $this->insert();
  141. }
  142. if ($num_matches > 1) {
  143. $message = t('ChadoRecord::save(). Could not save the record into the table, !table. '.
  144. 'Multiple records already exist that match the values: !values. '.
  145. 'Please provide a set of values that can uniquely identify a record.',
  146. ['!table' => $this->table_name, '!values' => print_r($this->values, TRUE), '!error' => $e->getMessage()]);
  147. throw new Exception($message);
  148. }
  149. }
  150. /**
  151. * Inserts the values of this object as a new record.
  152. *
  153. * @throws Exception
  154. */
  155. public function insert() {
  156. // Make sure we have values for this record before inserting.
  157. if (empty($this->values)) {
  158. $message = t('ChadoRecord::insert(). Could not insert a record into the table, !table, without any values.',
  159. ['!table' => $this->table_name]);
  160. throw new Exception($message);
  161. }
  162. // Build the SQL statement for insertion.
  163. $insert_cols = [];
  164. $insert_vals = [];
  165. $insert_args = [];
  166. foreach ($this->values as $column => $value) {
  167. $insert_cols[] = $column;
  168. $insert_vals[] = ':' . $column;
  169. $insert_args[':' . $column] = $value;
  170. }
  171. $sql = 'INSERT INTO {' . $this->table_name . '} (' .
  172. implode(", ", $insert_cols) . ') VALUES (' .
  173. implode(", ", $insert_vals) . ')';
  174. try {
  175. chado_query($sql, $insert_args);
  176. // TODO: we can speed up inserts if we can find a way to not have to
  177. // run the find(), but get the newly inserted record_id directly
  178. // from the insert command.
  179. $this->find();
  180. }
  181. catch (Exception $e) {
  182. $message = t('ChadoRecord::insert(). Could not insert a record into the table, !table, with the following values: !values. ERROR: !error',
  183. ['!table' => $this->table_name, '!values' => print_r($this->values, TRUE), '!error' => $e->getMessage()]);
  184. throw new Exception($message);
  185. }
  186. }
  187. /**
  188. * Updates the values of this object as a new record.
  189. *
  190. * @throws Exception
  191. */
  192. public function update() {
  193. // Make sure we have values for this record before updating.
  194. if (empty($this->values)) {
  195. $message = t('ChadoRecord::update(). Could not update a record into the table, !table, without any values.',
  196. ['!table' => $this->table_name]);
  197. throw new Exception($message);
  198. }
  199. // We have to have a record ID for the record to update.
  200. if (!$this->record_id) {
  201. $message = t('ChadoRecord::update(). Could not update a record in the table, !table, without a record ID.',
  202. ['!table' => $this->table_name]);
  203. throw new Exception($message);
  204. }
  205. // Build the SQL statement for updating.
  206. $update_args = [];
  207. $sql = 'UPDATE {' . $this->table_name . '} SET ';
  208. foreach ($this->values as $column => $value) {
  209. // We're not updating the primary key so skip that if it's in the values.
  210. if ($column == $this->pkey) {
  211. continue;
  212. }
  213. $sql .= $column . ' = :' . $column . ', ';
  214. $update_args[':' . $column] = $value;
  215. }
  216. // Remove the trailing comma and space.
  217. $sql = substr($sql, 0, -2);
  218. $sql .= ' WHERE ' . $this->pkey . ' = :record_id';
  219. $update_args[':record_id'] = $this->record_id;
  220. // Now try the update.
  221. try {
  222. chado_query($sql, $update_args);
  223. }
  224. catch (Exception $e) {
  225. $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',
  226. ['!table' => $this->table_name,
  227. '!record_id' => $this->record_id,
  228. '!values' => print_r($this->values, TRUE),
  229. '!error' => $e->getMessage()]);
  230. throw new Exception($message);
  231. }
  232. }
  233. /**
  234. * Deletes the record that matches the given values.
  235. *
  236. * A record ID must be part of the current values.
  237. *
  238. * @throws Exception
  239. */
  240. public function delete() {
  241. // We have to have a record ID for the record to be deleted.
  242. if (!$this->record_id) {
  243. $message = t('ChadoRecord::delete(). Could not delete a record in the table, !table, without a record ID.',
  244. ['!table' => $this->table_name]);
  245. throw new Exception($message);
  246. }
  247. try {
  248. $sql = 'DELETE FROM {' . $this->table_name . '} WHERE ' . $this->pkey . ' = :record_id';
  249. chado_query($sql, [':record_id' => $this->record_id]);
  250. }
  251. catch (Exception $e) {
  252. $message = t('ChadoRecord::delete(). Could not delete a record in the table, !table, with !record_id as the record ID. ERROR: !error',
  253. ['!table' => $this->table_name,
  254. '!record_id' => $this->record_id,
  255. '!error' => $e->getMessage()]);
  256. throw new Exception($message);
  257. }
  258. }
  259. /**
  260. * A general-purpose setter function to set the column values for the record.
  261. *
  262. * This function should be used prior to insert or update of a record. For
  263. * an update, be sure to include the record ID in the list of values passed
  264. * to the function.
  265. *
  266. * @param array $values
  267. * An associative array where the keys are the table column names and
  268. * the values are the record values for each column.
  269. *
  270. * @throws Exception
  271. */
  272. public function setValues($values) {
  273. // Intiailze the values array.
  274. $this->values = [];
  275. // Add the values provided into the values property.
  276. foreach ($values as $column => $value) {
  277. if (in_array($column, $this->column_names)) {
  278. $this->values[$column] = $value;
  279. }
  280. else {
  281. $message = t('ChadoRecord::setValues(). The column named, "!column", does not exist in table: "!table". Values: !values".',
  282. ['!column' => $column, '!table' => $this->table_name, '!values' => print_r($values, TRUE)]);
  283. throw new Exception($message);
  284. }
  285. }
  286. // Make sure that the user did not miss any required columns or has
  287. // set a column to be NULL when it doesn't allow NULLs.
  288. foreach ($this->required_cols as $rcol) {
  289. // It's okay if the primary key is missing, esepecially if the user
  290. // wants to use the find() or insert() functions.
  291. if ($rcol == $this->pkey) {
  292. continue;
  293. }
  294. if (in_array($rcol, array_keys($this->values)) and $this->values[$rcol] === '__NULL__') {
  295. $message = t('ChadoRecord::setValues(). The column named, "!column", requires a value for the table: "!table".',
  296. ['!column' => $rcol, '!table' => $this->table_name]);
  297. throw new Exception($message);
  298. }
  299. }
  300. // Check to see if the user provided the primary key (record_id).
  301. if (in_array($this->pkey, array_keys($values))) {
  302. $this->record_id = $values[$this->pkey];
  303. }
  304. }
  305. /**
  306. * Returns all values for the record.
  307. *
  308. * @return array
  309. */
  310. public function getValues() {
  311. return $this->values;
  312. }
  313. /**
  314. * Sets the value for a specific column.
  315. *
  316. * @param string $column_name
  317. * The name of the column to which the value should be set.
  318. * @param $value
  319. * The value to set.
  320. */
  321. public function setValue($column_name, $value) {
  322. // Make sure the column is valid.
  323. if (!in_array($column_name, $this->column_names)) {
  324. $message = t('ChadoRecord::setValue(). The column named, "!column", does not exist in table: "!table".',
  325. ['!column' => $column_name, '!table' => $this->table_name]);
  326. throw new Exception($message);
  327. }
  328. // Make sure that the value is not NULL if this is a required field.
  329. if (!in_array($column_name, $this->required_cols) and $value == '__NULL__') {
  330. $message = t('ChadoRecord::setValue(). The column named, "!column", requires a value for the table: "!table".',
  331. ['!column' => $column_name, '!table' => $this->table_name]);
  332. throw new Exception($message);
  333. }
  334. $this->values[$column_name] = $value;
  335. }
  336. /**
  337. * Returns the value of a specific column.
  338. *
  339. * @param string $column_name
  340. * The name of a column from the table from which to retrieve the value.
  341. */
  342. public function getValue($column_name) {
  343. // Make sure the column is valid.
  344. if (!in_array($column_name, $this->column_names)) {
  345. $message = t('ChadoRecord::getValue(). The column named, "!column", does not exist in table: "!table".',
  346. ['!column' => $column_name, '!table' => $this->table_name]);
  347. throw new Exception($message);
  348. }
  349. return $this->values[$column_name];
  350. }
  351. /**
  352. * Uses the current values given to this object to find a record.
  353. *
  354. * Use the setValues function first to set values for searching, then call
  355. * this function to find matching record. The values provided to the
  356. * setValues function must uniquely identify a record.
  357. *
  358. * @return
  359. * The number of matches found. If 1 is returned then the query
  360. * successfully found a match. If 0 then no matching records were found.
  361. *
  362. * @throws Exception
  363. */
  364. public function find() {
  365. // Make sure we have values for this record before searching.
  366. if (empty($this->values)) {
  367. $message = t('ChadoRecord::find(). Could not find a record from the table, !table, without any values.',
  368. ['!table' => $this->table_name]);
  369. throw new Exception($message);
  370. }
  371. // Build the SQL statement for searching.
  372. $select_args = [];
  373. $sql = 'SELECT * FROM {' . $this->table_name . '} WHERE 1=1 ';
  374. foreach ($this->values as $column => $value) {
  375. $sql .= ' AND ' . $column . ' = :' . $column;
  376. $select_args[':' . $column] = $value;
  377. }
  378. try {
  379. $results = chado_query($sql, $select_args);
  380. }
  381. catch (Exception $e) {
  382. $message = t('ChadoRecord::find(). Could not find a record in the table, !table, with the following values: !values. ERROR: !error',
  383. ['!table' => $this->table_name, '!values' => print_r($this->values, TRUE), '!error' => $e->getMessage()]);
  384. throw new Exception($message);
  385. }
  386. // If we only have a single match then we're good and we can update the
  387. // values for this object.
  388. $num_matches = $results->rowCount();
  389. if ($num_matches == 1) {
  390. $record = $results->fetchAssoc();
  391. $this->values = [];
  392. foreach ($record as $column => $value) {
  393. $this->values[$column] = $value;
  394. }
  395. $this->record_id = $record[$this->pkey];
  396. }
  397. // Return the number of matches.
  398. return $num_matches;
  399. }
  400. }