adapter.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /**
  3. * Copyright (c) 2013 Bart Visscher <bartv@thisnet.nl>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. */
  8. namespace OC\DB;
  9. /**
  10. * This handles the way we use to write queries, into something that can be
  11. * handled by the database abstraction layer.
  12. */
  13. class Adapter {
  14. /**
  15. * @var \OC\DB\Connection $conn
  16. */
  17. protected $conn;
  18. public function __construct($conn) {
  19. $this->conn = $conn;
  20. }
  21. /**
  22. * @param string $table name
  23. * @return int id of last insert statement
  24. */
  25. public function lastInsertId($table) {
  26. return $this->conn->realLastInsertId($table);
  27. }
  28. /**
  29. * @param string $statement that needs to be changed so the db can handle it
  30. * @return string changed statement
  31. */
  32. public function fixupStatement($statement) {
  33. return $statement;
  34. }
  35. /**
  36. * @brief insert the @input values when they do not exist yet
  37. * @param string $table name
  38. * @param array $input key->value pairs
  39. * @return int count of inserted rows
  40. */
  41. public function insertIfNotExist($table, $input) {
  42. $query = 'INSERT INTO `' .$table . '` (`'
  43. . implode('`,`', array_keys($input)) . '`) SELECT '
  44. . str_repeat('?,', count($input)-1).'? ' // Is there a prettier alternative?
  45. . 'FROM `' . $table . '` WHERE ';
  46. foreach($input as $key => $value) {
  47. $query .= '`' . $key . '` = ? AND ';
  48. }
  49. $query = substr($query, 0, strlen($query) - 5);
  50. $query .= ' HAVING COUNT(*) = 0';
  51. $inserts = array_values($input);
  52. $inserts = array_merge($inserts, $inserts);
  53. try {
  54. return $this->conn->executeUpdate($query, $inserts);
  55. } catch(\Doctrine\DBAL\DBALException $e) {
  56. $entry = 'DB Error: "'.$e->getMessage() . '"<br />';
  57. $entry .= 'Offending command was: ' . $query.'<br />';
  58. \OC_Log::write('core', $entry, \OC_Log::FATAL);
  59. error_log('DB error: ' . $entry);
  60. \OC_Template::printErrorPage( $entry );
  61. }
  62. }
  63. }