ChadoRecord.inc 15 KB

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