Connection.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace PHPixie\DB;
  3. /**
  4. * Database related functions. Creates connections,
  5. * executes queries and returns results. It is also the
  6. * generic connection class used by drivers.
  7. * @package Database
  8. */
  9. abstract class Connection
  10. {
  11. public $pixie;
  12. public function __construct($pixie, $config) {
  13. $this->pixie = $pixie;
  14. }
  15. /**
  16. * Executes a prepared statement query
  17. *
  18. * @param string $query A prepared statement query
  19. * @param array $params Parameters for the query
  20. * @return Result_Database
  21. * @see Result_Database
  22. */
  23. public abstract function execute($query, $params = array());
  24. /**
  25. * Builds a new Query to the database
  26. *
  27. * @param string $type Query type. Available types: select, update, insert, delete, count
  28. * @return Result_Database
  29. * @see Query_Database
  30. */
  31. public abstract function query($type);
  32. /**
  33. * Gets the id of the last inserted row.
  34. *
  35. * @return mixed The id of the last inserted row
  36. */
  37. public abstract function insert_id();
  38. /**
  39. * Gets column names for the specified table
  40. *
  41. * @param string $table Name of the table to get columns from
  42. * @return array Array of column names
  43. */
  44. public abstract function list_columns($table);
  45. /**
  46. * Executes a named query where parameters are passed as an associative array
  47. * Example:
  48. * <code>
  49. * $result=$db->namedQuery("SELECT * FROM fairies where name = :name",array('name'=>'Tinkerbell'));
  50. * </code>
  51. *
  52. * @param string $query A named query
  53. * @param array $params Associative array of parameters
  54. * @return Result_Database Current drivers implementation of Result_Database
  55. */
  56. public function named_query($query, $params = array())
  57. {
  58. $bind = array();
  59. preg_match_all('#:(\w+)#is', $query, $matches, PREG_SET_ORDER);
  60. foreach ($matches as $match)
  61. {
  62. if (isset($params[$match[1]]))
  63. {
  64. $query = preg_replace("#{$match[0]}#", '?', $query, 1);
  65. $bind[] = $params[$match[1]];
  66. }
  67. }
  68. return $this->execute($query, $bind);
  69. }
  70. /**
  71. * Returns an Expression representation of the value.
  72. * Values wrapped inside Expression are not escaped in queries
  73. *
  74. * @param mixed $value Value to be wrapped
  75. * @return \PHPixie\Db\Expression Raw value that will not be escaped during query building
  76. */
  77. public function expr($value)
  78. {
  79. return $this->phpixie->db->expr($value);
  80. }
  81. }