PageRenderTime 27ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Connection.php

http://github.com/kla/php-activerecord
PHP | 550 lines | 276 code | 65 blank | 209 comment | 34 complexity | f3c07bff994cda26def46fefc1cb59cc MD5 | raw file
  1. <?php
  2. /**
  3. * @package ActiveRecord
  4. */
  5. namespace ActiveRecord;
  6. require_once 'Column.php';
  7. use PDO;
  8. use PDOException;
  9. use Closure;
  10. /**
  11. * The base class for database connection adapters.
  12. *
  13. * @package ActiveRecord
  14. */
  15. abstract class Connection
  16. {
  17. /**
  18. * The DateTime format to use when translating other DateTime-compatible objects.
  19. *
  20. * NOTE!: The DateTime "format" used must not include a time-zone (name, abbreviation, etc) or offset.
  21. * Including one will cause PHP to ignore the passed in time-zone in the 3rd argument.
  22. * See bug: https://bugs.php.net/bug.php?id=61022
  23. *
  24. * @var string
  25. */
  26. const DATETIME_TRANSLATE_FORMAT = 'Y-m-d\TH:i:s';
  27. /**
  28. * The PDO connection object.
  29. * @var mixed
  30. */
  31. public $connection;
  32. /**
  33. * The last query run.
  34. * @var string
  35. */
  36. public $last_query;
  37. /**
  38. * Switch for logging.
  39. *
  40. * @var bool
  41. */
  42. private $logging = false;
  43. /**
  44. * Contains a Logger object that must impelement a log() method.
  45. *
  46. * @var object
  47. */
  48. private $logger;
  49. /**
  50. * The name of the protocol that is used.
  51. * @var string
  52. */
  53. public $protocol;
  54. /**
  55. * Database's date format
  56. * @var string
  57. */
  58. static $date_format = 'Y-m-d';
  59. /**
  60. * Database's datetime format
  61. * @var string
  62. */
  63. static $datetime_format = 'Y-m-d H:i:s T';
  64. /**
  65. * Default PDO options to set for each connection.
  66. * @var array
  67. */
  68. static $PDO_OPTIONS = array(
  69. PDO::ATTR_CASE => PDO::CASE_LOWER,
  70. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  71. PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
  72. PDO::ATTR_STRINGIFY_FETCHES => false);
  73. /**
  74. * The quote character for stuff like column and field names.
  75. * @var string
  76. */
  77. static $QUOTE_CHARACTER = '`';
  78. /**
  79. * Default port.
  80. * @var int
  81. */
  82. static $DEFAULT_PORT = 0;
  83. /**
  84. * Retrieve a database connection.
  85. *
  86. * @param string $connection_string_or_connection_name A database connection string (ex. mysql://user:pass@host[:port]/dbname)
  87. * Everything after the protocol:// part is specific to the connection adapter.
  88. * OR
  89. * A connection name that is set in ActiveRecord\Config
  90. * If null it will use the default connection specified by ActiveRecord\Config->set_default_connection
  91. * @return Connection
  92. * @see parse_connection_url
  93. */
  94. public static function instance($connection_string_or_connection_name=null)
  95. {
  96. $config = Config::instance();
  97. if (strpos($connection_string_or_connection_name, '://') === false)
  98. {
  99. $connection_string = $connection_string_or_connection_name ?
  100. $config->get_connection($connection_string_or_connection_name) :
  101. $config->get_default_connection_string();
  102. }
  103. else
  104. $connection_string = $connection_string_or_connection_name;
  105. if (!$connection_string)
  106. throw new DatabaseException("Empty connection string");
  107. $info = static::parse_connection_url($connection_string);
  108. $fqclass = static::load_adapter_class($info->protocol);
  109. try {
  110. $connection = new $fqclass($info);
  111. $connection->protocol = $info->protocol;
  112. $connection->logging = $config->get_logging();
  113. $connection->logger = $connection->logging ? $config->get_logger() : null;
  114. if (isset($info->charset))
  115. $connection->set_encoding($info->charset);
  116. } catch (PDOException $e) {
  117. throw new DatabaseException($e);
  118. }
  119. return $connection;
  120. }
  121. /**
  122. * Loads the specified class for an adapter.
  123. *
  124. * @param string $adapter Name of the adapter.
  125. * @return string The full name of the class including namespace.
  126. */
  127. private static function load_adapter_class($adapter)
  128. {
  129. $class = ucwords($adapter) . 'Adapter';
  130. $fqclass = 'ActiveRecord\\' . $class;
  131. $source = __DIR__ . "/adapters/$class.php";
  132. if (!file_exists($source))
  133. throw new DatabaseException("$fqclass not found!");
  134. require_once($source);
  135. return $fqclass;
  136. }
  137. /**
  138. * Use this for any adapters that can take connection info in the form below
  139. * to set the adapters connection info.
  140. *
  141. * <code>
  142. * protocol://username:password@host[:port]/dbname
  143. * protocol://urlencoded%20username:urlencoded%20password@host[:port]/dbname?decode=true
  144. * protocol://username:password@unix(/some/file/path)/dbname
  145. * </code>
  146. *
  147. * Sqlite has a special syntax, as it does not need a database name or user authentication:
  148. *
  149. * <code>
  150. * sqlite://file.db
  151. * sqlite://../relative/path/to/file.db
  152. * sqlite://unix(/absolute/path/to/file.db)
  153. * sqlite://windows(c%2A/absolute/path/to/file.db)
  154. * </code>
  155. *
  156. * @param string $connection_url A connection URL
  157. * @return object the parsed URL as an object.
  158. */
  159. public static function parse_connection_url($connection_url)
  160. {
  161. $url = @parse_url($connection_url);
  162. if (!isset($url['host']))
  163. throw new DatabaseException('Database host must be specified in the connection string. If you want to specify an absolute filename, use e.g. sqlite://unix(/path/to/file)');
  164. $info = new \stdClass();
  165. $info->protocol = $url['scheme'];
  166. $info->host = $url['host'];
  167. $info->db = isset($url['path']) ? substr($url['path'], 1) : null;
  168. $info->user = isset($url['user']) ? $url['user'] : null;
  169. $info->pass = isset($url['pass']) ? $url['pass'] : null;
  170. $allow_blank_db = ($info->protocol == 'sqlite');
  171. if ($info->host == 'unix(')
  172. {
  173. $socket_database = $info->host . '/' . $info->db;
  174. if ($allow_blank_db)
  175. $unix_regex = '/^unix\((.+)\)\/?().*$/';
  176. else
  177. $unix_regex = '/^unix\((.+)\)\/(.+)$/';
  178. if (preg_match_all($unix_regex, $socket_database, $matches) > 0)
  179. {
  180. $info->host = $matches[1][0];
  181. $info->db = $matches[2][0];
  182. }
  183. } elseif (substr($info->host, 0, 8) == 'windows(')
  184. {
  185. $info->host = urldecode(substr($info->host, 8) . '/' . substr($info->db, 0, -1));
  186. $info->db = null;
  187. }
  188. if ($allow_blank_db && $info->db)
  189. $info->host .= '/' . $info->db;
  190. if (isset($url['port']))
  191. $info->port = $url['port'];
  192. if (strpos($connection_url, 'decode=true') !== false)
  193. {
  194. if ($info->user)
  195. $info->user = urldecode($info->user);
  196. if ($info->pass)
  197. $info->pass = urldecode($info->pass);
  198. }
  199. if (isset($url['query']))
  200. {
  201. foreach (explode('/&/', $url['query']) as $pair) {
  202. list($name, $value) = explode('=', $pair);
  203. if ($name == 'charset')
  204. $info->charset = $value;
  205. }
  206. }
  207. return $info;
  208. }
  209. /**
  210. * Class Connection is a singleton. Access it via instance().
  211. *
  212. * @param array $info Array containing URL parts
  213. * @return Connection
  214. */
  215. protected function __construct($info)
  216. {
  217. try {
  218. // unix sockets start with a /
  219. if ($info->host[0] != '/')
  220. {
  221. $host = "host=$info->host";
  222. if (isset($info->port))
  223. $host .= ";port=$info->port";
  224. }
  225. else
  226. $host = "unix_socket=$info->host";
  227. $this->connection = new PDO("$info->protocol:$host;dbname=$info->db", $info->user, $info->pass, static::$PDO_OPTIONS);
  228. } catch (PDOException $e) {
  229. throw new DatabaseException($e);
  230. }
  231. }
  232. /**
  233. * Retrieves column meta data for the specified table.
  234. *
  235. * @param string $table Name of a table
  236. * @return array An array of {@link Column} objects.
  237. */
  238. public function columns($table)
  239. {
  240. $columns = array();
  241. $sth = $this->query_column_info($table);
  242. while (($row = $sth->fetch())) {
  243. $c = $this->create_column($row);
  244. $columns[$c->name] = $c;
  245. }
  246. return $columns;
  247. }
  248. /**
  249. * Escapes quotes in a string.
  250. *
  251. * @param string $string The string to be quoted.
  252. * @return string The string with any quotes in it properly escaped.
  253. */
  254. public function escape($string)
  255. {
  256. return $this->connection->quote($string);
  257. }
  258. /**
  259. * Retrieve the insert id of the last model saved.
  260. *
  261. * @param string $sequence Optional name of a sequence to use
  262. * @return int
  263. */
  264. public function insert_id($sequence=null)
  265. {
  266. return $this->connection->lastInsertId($sequence);
  267. }
  268. /**
  269. * Execute a raw SQL query on the database.
  270. *
  271. * @param string $sql Raw SQL string to execute.
  272. * @param array &$values Optional array of bind values
  273. * @return mixed A result set object
  274. */
  275. public function query($sql, &$values=array())
  276. {
  277. if ($this->logging)
  278. {
  279. $this->logger->log($sql);
  280. if ( $values ) $this->logger->log($values);
  281. }
  282. $this->last_query = $sql;
  283. try {
  284. if (!($sth = $this->connection->prepare($sql)))
  285. throw new DatabaseException($this);
  286. } catch (PDOException $e) {
  287. throw new DatabaseException($this);
  288. }
  289. $sth->setFetchMode(PDO::FETCH_ASSOC);
  290. try {
  291. if (!$sth->execute($values))
  292. throw new DatabaseException($this);
  293. } catch (PDOException $e) {
  294. throw new DatabaseException($e);
  295. }
  296. return $sth;
  297. }
  298. /**
  299. * Execute a query that returns maximum of one row with one field and return it.
  300. *
  301. * @param string $sql Raw SQL string to execute.
  302. * @param array &$values Optional array of values to bind to the query.
  303. * @return string
  304. */
  305. public function query_and_fetch_one($sql, &$values=array())
  306. {
  307. $sth = $this->query($sql, $values);
  308. $row = $sth->fetch(PDO::FETCH_NUM);
  309. return $row[0];
  310. }
  311. /**
  312. * Execute a raw SQL query and fetch the results.
  313. *
  314. * @param string $sql Raw SQL string to execute.
  315. * @param Closure $handler Closure that will be passed the fetched results.
  316. */
  317. public function query_and_fetch($sql, Closure $handler)
  318. {
  319. $sth = $this->query($sql);
  320. while (($row = $sth->fetch(PDO::FETCH_ASSOC)))
  321. $handler($row);
  322. }
  323. /**
  324. * Returns all tables for the current database.
  325. *
  326. * @return array Array containing table names.
  327. */
  328. public function tables()
  329. {
  330. $tables = array();
  331. $sth = $this->query_for_tables();
  332. while (($row = $sth->fetch(PDO::FETCH_NUM)))
  333. $tables[] = $row[0];
  334. return $tables;
  335. }
  336. /**
  337. * Starts a transaction.
  338. */
  339. public function transaction()
  340. {
  341. if (!$this->connection->beginTransaction())
  342. throw new DatabaseException($this);
  343. }
  344. /**
  345. * Commits the current transaction.
  346. */
  347. public function commit()
  348. {
  349. if (!$this->connection->commit())
  350. throw new DatabaseException($this);
  351. }
  352. /**
  353. * Rollback a transaction.
  354. */
  355. public function rollback()
  356. {
  357. if (!$this->connection->rollback())
  358. throw new DatabaseException($this);
  359. }
  360. /**
  361. * Tells you if this adapter supports sequences or not.
  362. *
  363. * @return boolean
  364. */
  365. function supports_sequences()
  366. {
  367. return false;
  368. }
  369. /**
  370. * Return a default sequence name for the specified table.
  371. *
  372. * @param string $table Name of a table
  373. * @param string $column_name Name of column sequence is for
  374. * @return string sequence name or null if not supported.
  375. */
  376. public function get_sequence_name($table, $column_name)
  377. {
  378. return "{$table}_seq";
  379. }
  380. /**
  381. * Return SQL for getting the next value in a sequence.
  382. *
  383. * @param string $sequence_name Name of the sequence
  384. * @return string
  385. */
  386. public function next_sequence_value($sequence_name)
  387. {
  388. return null;
  389. }
  390. /**
  391. * Quote a name like table names and field names.
  392. *
  393. * @param string $string String to quote.
  394. * @return string
  395. */
  396. public function quote_name($string)
  397. {
  398. return $string[0] === static::$QUOTE_CHARACTER || $string[strlen($string) - 1] === static::$QUOTE_CHARACTER ?
  399. $string : static::$QUOTE_CHARACTER . $string . static::$QUOTE_CHARACTER;
  400. }
  401. /**
  402. * Return a date time formatted into the database's date format.
  403. *
  404. * @param DateTime $datetime The DateTime object
  405. * @return string
  406. */
  407. public function date_to_string($datetime)
  408. {
  409. return $datetime->format(static::$date_format);
  410. }
  411. /**
  412. * Return a date time formatted into the database's datetime format.
  413. *
  414. * @param DateTime $datetime The DateTime object
  415. * @return string
  416. */
  417. public function datetime_to_string($datetime)
  418. {
  419. return $datetime->format(static::$datetime_format);
  420. }
  421. /**
  422. * Converts a string representation of a datetime into a DateTime object.
  423. *
  424. * @param string $string A datetime in the form accepted by date_create()
  425. * @return object The date_class set in Config
  426. */
  427. public function string_to_datetime($string)
  428. {
  429. $date = date_create($string);
  430. $errors = \DateTime::getLastErrors();
  431. if ($errors['warning_count'] > 0 || $errors['error_count'] > 0)
  432. return null;
  433. $date_class = Config::instance()->get_date_class();
  434. return $date_class::createFromFormat(
  435. static::DATETIME_TRANSLATE_FORMAT,
  436. $date->format(static::DATETIME_TRANSLATE_FORMAT),
  437. $date->getTimezone()
  438. );
  439. }
  440. /**
  441. * Adds a limit clause to the SQL query.
  442. *
  443. * @param string $sql The SQL statement.
  444. * @param int $offset Row offset to start at.
  445. * @param int $limit Maximum number of rows to return.
  446. * @return string The SQL query that will limit results to specified parameters
  447. */
  448. abstract function limit($sql, $offset, $limit);
  449. /**
  450. * Query for column meta info and return statement handle.
  451. *
  452. * @param string $table Name of a table
  453. * @return PDOStatement
  454. */
  455. abstract public function query_column_info($table);
  456. /**
  457. * Query for all tables in the current database. The result must only
  458. * contain one column which has the name of the table.
  459. *
  460. * @return PDOStatement
  461. */
  462. abstract function query_for_tables();
  463. /**
  464. * Executes query to specify the character set for this connection.
  465. */
  466. abstract function set_encoding($charset);
  467. /*
  468. * Returns an array mapping of native database types
  469. */
  470. abstract public function native_database_types();
  471. /**
  472. * Specifies whether or not adapter can use LIMIT/ORDER clauses with DELETE & UPDATE operations
  473. *
  474. * @internal
  475. * @returns boolean (FALSE by default)
  476. */
  477. public function accepts_limit_and_order_for_update_and_delete()
  478. {
  479. return false;
  480. }
  481. }