Sqlite.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. * PHP Version 5.4
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @since CakePHP(tm) v 3.0.0
  15. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  16. */
  17. namespace Cake\Database\Driver;
  18. use Cake\Database\Dialect\SqliteDialectTrait;
  19. use Cake\Database\Statement\PDOStatement;
  20. use Cake\Database\Statement\SqliteStatement;
  21. use PDO;
  22. class Sqlite extends \Cake\Database\Driver {
  23. use PDODriverTrait;
  24. use SqliteDialectTrait;
  25. /**
  26. * Base configuration settings for Sqlite driver
  27. *
  28. * @var array
  29. */
  30. protected $_baseConfig = [
  31. 'persistent' => false,
  32. 'login' => null,
  33. 'password' => null,
  34. 'database' => ':memory:',
  35. 'encoding' => 'utf8',
  36. 'flags' => [],
  37. 'init' => [],
  38. 'dsn' => null
  39. ];
  40. /**
  41. * Establishes a connection to the databse server
  42. *
  43. * @return boolean true on success
  44. */
  45. public function connect() {
  46. if ($this->_connection) {
  47. return true;
  48. }
  49. $config = $this->_config;
  50. $config['flags'] += [
  51. PDO::ATTR_PERSISTENT => $config['persistent'],
  52. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  53. ];
  54. if (empty($config['dsn'])) {
  55. $config['dsn'] = "sqlite:{$config['database']}";
  56. }
  57. $this->_connect($config);
  58. if (!empty($config['init'])) {
  59. foreach ((array)$config['init'] as $command) {
  60. $this->connection()->exec($command);
  61. }
  62. }
  63. return true;
  64. }
  65. /**
  66. * Returns whether php is able to use this driver for connecting to database
  67. *
  68. * @return boolean true if it is valid to use this driver
  69. */
  70. public function enabled() {
  71. return in_array('sqlite', PDO::getAvailableDrivers());
  72. }
  73. /**
  74. * Prepares a sql statement to be executed
  75. *
  76. * @param string $sql
  77. * @return Cake\Database\Statement
  78. */
  79. public function prepare($sql) {
  80. $this->connect();
  81. $statement = $this->_connection->prepare($sql);
  82. return new SqliteStatement(new PDOStatement($statement, $this), $this);
  83. }
  84. }