ChadoRecord.inc 15 KB

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