PostgreSql.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2013, Union of RAD (http://union-of-rad.org)
  6. * @license http://opensource.org/licenses/bsd-license.php The BSD License
  7. */
  8. namespace lithium\data\source\database\adapter;
  9. use PDO;
  10. use PDOException;
  11. /**
  12. * Extends the `Database` class to implement the necessary SQL-formatting and resultset-fetching
  13. * features for working with PostgreSQL databases.
  14. *
  15. * For more information on configuring the database connection, see the `__construct()` method.
  16. *
  17. * @see lithium\data\source\database\adapter\PostgreSql::__construct()
  18. */
  19. class PostgreSql extends \lithium\data\source\Database {
  20. /**
  21. * PostgreSQL column type definitions.
  22. *
  23. * @var array
  24. */
  25. protected $_columns = array(
  26. 'primary_key' => array('name' => 'SERIAL not null'),
  27. 'string' => array('name' => 'varchar', 'length' => 255),
  28. 'text' => array('name' => 'text'),
  29. 'integer' => array('name' => 'integer', 'formatter' => 'intval'),
  30. 'float' => array('name' => 'float', 'formatter' => 'floatval'),
  31. 'datetime' => array(
  32. 'name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'
  33. ),
  34. 'timestamp' => array(
  35. 'name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'
  36. ),
  37. 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
  38. 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
  39. 'binary' => array('name' => 'bytea'),
  40. 'boolean' => array('name' => 'boolean'),
  41. 'number' => array('name' => 'numeric'),
  42. 'inet' => array('name' => 'inet')
  43. );
  44. /**
  45. * Pair of opening and closing quote characters used for quoting identifiers in queries.
  46. *
  47. * @var array
  48. */
  49. protected $_quotes = array('"', '"');
  50. /**
  51. * PostgreSQL-specific value denoting whether or not table aliases should be used in DELETE and
  52. * UPDATE queries.
  53. *
  54. * @var boolean
  55. */
  56. protected $_useAlias = true;
  57. /**
  58. * Constructs the PostgreSQL adapter and sets the default port to 5432.
  59. *
  60. * @see lithium\data\source\Database::__construct()
  61. * @see lithium\data\Source::__construct()
  62. * @see lithium\data\Connections::add()
  63. * @param array $config Configuration options for this class. For additional configuration,
  64. * see `lithium\data\source\Database` and `lithium\data\Source`. Available options
  65. * defined by this class:
  66. * - `'database'`: The name of the database to connect to. Defaults to 'lithium'.
  67. * - `'host'`: The IP or machine name where PostgreSQL is running, followed by a colon,
  68. * followed by a port number or socket. Defaults to `'localhost:5432'`.
  69. * - `'persistent'`: If a persistent connection (if available) should be made.
  70. * Defaults to true.
  71. * - `'schema'`: The name of the database schema to use. Defaults to 'public'
  72. *
  73. * Typically, these parameters are set in `Connections::add()`, when adding the adapter to the
  74. * list of active connections.
  75. */
  76. public function __construct(array $config = array()) {
  77. $defaults = array(
  78. 'host' => 'localhost:5432',
  79. 'encoding' => null,
  80. 'schema' => 'public',
  81. 'timezone' => null
  82. );
  83. parent::__construct($config + $defaults);
  84. }
  85. /**
  86. * Check for required PHP extension, or supported database feature.
  87. *
  88. * @param string $feature Test for support for a specific feature, i.e. `"transactions"` or
  89. * `"arrays"`.
  90. * @return boolean Returns `true` if the particular feature (or if PostgreSQL) support is
  91. * enabled, otherwise `false`.
  92. */
  93. public static function enabled($feature = null) {
  94. if (!$feature) {
  95. return extension_loaded('pdo_pgsql');
  96. }
  97. $features = array(
  98. 'arrays' => false,
  99. 'transactions' => true,
  100. 'booleans' => true,
  101. 'relationships' => true
  102. );
  103. return isset($features[$feature]) ? $features[$feature] : null;
  104. }
  105. /**
  106. * Connects to the database using the options provided to the class constructor.
  107. *
  108. * @return boolean Returns `true` if a database connection could be established, otherwise
  109. * `false`.
  110. */
  111. public function connect() {
  112. if (!$this->_config['dsn']) {
  113. $host = $this->_config['host'];
  114. list($host, $port) = explode(':', $host) + array(1 => "5432");
  115. $dsn = "pgsql:host=%s;port=%s;dbname=%s";
  116. $this->_config['dsn'] = sprintf($dsn, $host, $port, $this->_config['database']);
  117. }
  118. if (!parent::connect()) {
  119. return false;
  120. }
  121. if ($this->_config['schema']) {
  122. $this->search_path($this->_config['schema']);
  123. }
  124. if ($this->_config['timezone']) {
  125. $this->timezone($this->_config['timezone']);
  126. }
  127. return true;
  128. }
  129. /**
  130. * Returns the list of tables in the currently-connected database.
  131. *
  132. * @param string $model The fully-name-spaced class name of the model object making the request.
  133. * @return array Returns an array of sources to which models can connect.
  134. * @filter This method can be filtered.
  135. */
  136. public function sources($model = null) {
  137. $_config = $this->_config;
  138. $params = compact('model');
  139. return $this->_filter(__METHOD__, $params, function($self, $params) use ($_config) {
  140. $schema = $self->connection->quote($_config['schema']);
  141. $sql = "SELECT table_name as name FROM INFORMATION_SCHEMA.tables";
  142. $sql .= " WHERE table_schema = {$schema}";
  143. if (!$result = $self->invokeMethod('_execute', array($sql))) {
  144. return null;
  145. }
  146. $sources = array();
  147. while ($data = $result->next()) {
  148. $sources[] = array_shift($data);
  149. }
  150. return $sources;
  151. });
  152. }
  153. /**
  154. * Gets the column schema for a given PostgreSQL table.
  155. *
  156. * @param mixed $entity Specifies the table name for which the schema should be returned, or
  157. * the class name of the model object requesting the schema, in which case the model
  158. * class will be queried for the correct table name.
  159. * @param array $fields Any schema data pre-defined by the model.
  160. * @param array $meta
  161. * @return array Returns an associative array describing the given table's schema, where the
  162. * array keys are the available fields, and the values are arrays describing each
  163. * field, containing the following keys:
  164. * - `'type'`: The field type name
  165. * @filter This method can be filtered.
  166. */
  167. public function describe($entity, $fields = array(), array $meta = array()) {
  168. $schema = $this->_config['schema'];
  169. $params = compact('entity', 'meta', 'fields', 'schema');
  170. return $this->_filter(__METHOD__, $params, function($self, $params) {
  171. extract($params);
  172. if ($fields) {
  173. return $self->invokeMethod('_instance', array('schema', compact('fields')));
  174. }
  175. $name = $self->connection->quote($self->invokeMethod('_entityName', array($entity)));
  176. $schema = $self->connection->quote($schema);
  177. $sql = "SELECT DISTINCT table_schema AS schema, column_name AS field, data_type AS type,
  178. is_nullable AS null, column_default AS default, ordinal_position AS position,
  179. character_maximum_length AS char_length, character_octet_length AS oct_length
  180. FROM information_schema.columns
  181. WHERE table_name = {$name} AND table_schema = {$schema} ORDER BY position";
  182. $columns = $self->connection->query($sql)->fetchAll(PDO::FETCH_ASSOC);
  183. $fields = array();
  184. foreach ($columns as $column) {
  185. $match = $self->invokeMethod('_column', array($column['type']));
  186. if (preg_match('/nextval\([\'"]?([\w.]+)/', $column['default'])) {
  187. $default = null;
  188. } else {
  189. $default = $column['default'];
  190. }
  191. $fields[$column['field']] = $match + array(
  192. 'null' => ($column['null'] == 'YES' ? true : false),
  193. 'default' => $default
  194. );
  195. if ($fields[$column['field']]['type'] == 'string') {
  196. $fields[$column['field']]['length'] = $column['char_length'];
  197. }
  198. }
  199. return $self->invokeMethod('_instance', array('schema', compact('fields')));
  200. });
  201. }
  202. /**
  203. * Gets or sets the search path for the connection
  204. * @param $search_path
  205. * @return mixed If setting the search_path; returns ture on success, else false
  206. * When getting, returns the search_path
  207. */
  208. public function search_path($search_path) {
  209. if (empty($search_path)) {
  210. $query = $this->connection->query('SHOW search_path');
  211. $search_path = $query->fetchColumn(1);
  212. return explode(",", $search_path);
  213. }
  214. try{
  215. $this->connection->exec("SET search_path TO ${search_path}");
  216. return true;
  217. } catch (PDOException $e) {
  218. return false;
  219. }
  220. }
  221. /**
  222. * Gets or sets the time zone for the connection
  223. * @param $timezone
  224. * @return mixed If setting the time zone; returns true on success, else false
  225. * When getting, returns the time zone
  226. */
  227. public function timezone($timezone = null) {
  228. if (empty($timezone)) {
  229. $query = $this->connection->query('SHOW TIME ZONE');
  230. return $query->fetchColumn();
  231. }
  232. try {
  233. $this->connection->exec("SET TIME ZONE '{$timezone}'");
  234. return true;
  235. } catch (PDOException $e) {
  236. return false;
  237. }
  238. }
  239. /**
  240. * Gets or sets the encoding for the connection.
  241. *
  242. * @param $encoding
  243. * @return mixed If setting the encoding; returns true on success, else false.
  244. * When getting, returns the encoding.
  245. */
  246. public function encoding($encoding = null) {
  247. $encodingMap = array('UTF-8' => 'UTF8');
  248. if (empty($encoding)) {
  249. $query = $this->connection->query("SHOW client_encoding");
  250. $encoding = $query->fetchColumn();
  251. return ($key = array_search($encoding, $encodingMap)) ? $key : $encoding;
  252. }
  253. $encoding = isset($encodingMap[$encoding]) ? $encodingMap[$encoding] : $encoding;
  254. try {
  255. $this->connection->exec("SET NAMES '{$encoding}'");
  256. return true;
  257. } catch (PDOException $e) {
  258. return false;
  259. }
  260. }
  261. /**
  262. * Converts a given value into the proper type based on a given schema definition.
  263. *
  264. * @see lithium\data\source\Database::schema()
  265. * @param mixed $value The value to be converted. Arrays will be recursively converted.
  266. * @param array $schema Formatted array from `lithium\data\source\Database::schema()`
  267. * @return mixed Value with converted type.
  268. */
  269. public function value($value, array $schema = array()) {
  270. if (($result = parent::value($value, $schema)) !== null) {
  271. return $result;
  272. }
  273. return $this->connection->quote((string) $value);
  274. }
  275. /**
  276. * Retrieves database error message and error code.
  277. *
  278. * @return array
  279. */
  280. public function error() {
  281. if ($error = $this->connection->errorInfo()) {
  282. return array($error[1], $error[2]);
  283. }
  284. return null;
  285. }
  286. public function alias($alias, $context) {
  287. if ($context->type() == 'update' || $context->type() == 'delete') {
  288. return;
  289. }
  290. return parent::alias($alias, $context);
  291. }
  292. /**
  293. * @todo Eventually, this will need to rewrite aliases for DELETE and UPDATE queries, same with
  294. * order().
  295. * @param string $conditions
  296. * @param string $context
  297. * @param array $options
  298. * @return void
  299. */
  300. public function conditions($conditions, $context, array $options = array()) {
  301. return parent::conditions($conditions, $context, $options);
  302. }
  303. /**
  304. * Execute a given query.
  305. *
  306. * @see lithium\data\source\Database::renderCommand()
  307. * @param string $sql The sql string to execute
  308. * @param array $options Available options:
  309. * @return resource Returns the result resource handle if the query is successful.
  310. * @filter
  311. */
  312. protected function _execute($sql, array $options = array()) {
  313. $conn = $this->connection;
  314. $params = compact('sql', 'options');
  315. return $this->_filter(__METHOD__, $params, function($self, $params) use ($conn) {
  316. $sql = $params['sql'];
  317. $options = $params['options'];
  318. try {
  319. $resource = $conn->query($sql);
  320. } catch(PDOException $e) {
  321. $self->invokeMethod('_error', array($sql));
  322. };
  323. return $self->invokeMethod('_instance', array('result', compact('resource')));
  324. });
  325. }
  326. /**
  327. * Gets the last auto-generated ID from the query that inserted a new record.
  328. *
  329. * @param object $query The `Query` object associated with the query which generated
  330. * @return mixed Returns the last inserted ID key for an auto-increment column or a column
  331. * bound to a sequence.
  332. */
  333. protected function _insertId($query) {
  334. $model = $query->model();
  335. $field = $model::key();
  336. $source = $model::meta('source');
  337. $sequence = "{$source}_{$field}_seq";
  338. $id = $this->connection->lastInsertId($sequence);
  339. return ($id && $id !== '0') ? $id : null;
  340. }
  341. /**
  342. * Converts database-layer column types to basic types.
  343. *
  344. * @param string $real Real database-layer column type (i.e. `"varchar(255)"`)
  345. * @return array Column type (i.e. "string") plus 'length' when appropriate.
  346. */
  347. protected function _column($real) {
  348. if (is_array($real)) {
  349. return $real['type'] . (isset($real['length']) ? "({$real['length']})" : '');
  350. }
  351. if (!preg_match('/(?P<type>\w+)(?:\((?P<length>[\d,]+)\))?/', $real, $column)) {
  352. return $real;
  353. }
  354. $column = array_intersect_key($column, array('type' => null, 'length' => null));
  355. if (isset($column['length']) && $column['length']) {
  356. $length = explode(',', $column['length']) + array(null, null);
  357. $column['length'] = $length[0] ? intval($length[0]) : null;
  358. $length[1] ? $column['precision'] = intval($length[1]) : null;
  359. }
  360. switch (true) {
  361. case in_array($column['type'], array('date', 'time', 'datetime')):
  362. return $column;
  363. case ($column['type'] == 'timestamp'):
  364. $column['type'] = 'datetime';
  365. break;
  366. case ($column['type'] == 'tinyint' && $column['length'] == '1'):
  367. case ($column['type'] == 'boolean'):
  368. return array('type' => 'boolean');
  369. break;
  370. case (strpos($column['type'], 'int') !== false):
  371. $column['type'] = 'integer';
  372. break;
  373. case (strpos($column['type'], 'char') !== false || $column['type'] == 'tinytext'):
  374. $column['type'] = 'string';
  375. break;
  376. case (strpos($column['type'], 'text') !== false):
  377. $column['type'] = 'text';
  378. break;
  379. case (strpos($column['type'], 'blob') !== false || $column['type'] == 'binary'):
  380. $column['type'] = 'binary';
  381. break;
  382. case preg_match('/float|double|decimal/', $column['type']):
  383. $column['type'] = 'float';
  384. break;
  385. default:
  386. $column['type'] = 'text';
  387. break;
  388. }
  389. return $column;
  390. }
  391. protected function _toNativeBoolean($value) {
  392. return $this->connection->quote($value ? 't' : 'f');
  393. }
  394. }
  395. ?>