Pgsql.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Db
  17. * @subpackage Adapter
  18. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. /**
  23. * @see Zend_Db_Adapter_Pdo_Abstract
  24. */
  25. require_once 'Zend/Db/Adapter/Pdo/Abstract.php';
  26. /**
  27. * Class for connecting to PostgreSQL databases and performing common operations.
  28. *
  29. * @category Zend
  30. * @package Zend_Db
  31. * @subpackage Adapter
  32. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  33. * @license http://framework.zend.com/license/new-bsd New BSD License
  34. */
  35. class Zend_Db_Adapter_Pdo_Pgsql extends Zend_Db_Adapter_Pdo_Abstract
  36. {
  37. /**
  38. * PDO type.
  39. *
  40. * @var string
  41. */
  42. protected $_pdoType = 'pgsql';
  43. /**
  44. * Keys are UPPERCASE SQL datatypes or the constants
  45. * Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
  46. *
  47. * Values are:
  48. * 0 = 32-bit integer
  49. * 1 = 64-bit integer
  50. * 2 = float or decimal
  51. *
  52. * @var array Associative array of datatypes to values 0, 1, or 2.
  53. */
  54. protected $_numericDataTypes = array(
  55. Zend_Db::INT_TYPE => Zend_Db::INT_TYPE,
  56. Zend_Db::BIGINT_TYPE => Zend_Db::BIGINT_TYPE,
  57. Zend_Db::FLOAT_TYPE => Zend_Db::FLOAT_TYPE,
  58. 'INTEGER' => Zend_Db::INT_TYPE,
  59. 'SERIAL' => Zend_Db::INT_TYPE,
  60. 'SMALLINT' => Zend_Db::INT_TYPE,
  61. 'BIGINT' => Zend_Db::BIGINT_TYPE,
  62. 'BIGSERIAL' => Zend_Db::BIGINT_TYPE,
  63. 'DECIMAL' => Zend_Db::FLOAT_TYPE,
  64. 'DOUBLE PRECISION' => Zend_Db::FLOAT_TYPE,
  65. 'NUMERIC' => Zend_Db::FLOAT_TYPE,
  66. 'REAL' => Zend_Db::FLOAT_TYPE
  67. );
  68. /**
  69. * Creates a PDO object and connects to the database.
  70. *
  71. * @return void
  72. * @throws Zend_Db_Adapter_Exception
  73. */
  74. protected function _connect()
  75. {
  76. if ($this->_connection) {
  77. return;
  78. }
  79. parent::_connect();
  80. if (!empty($this->_config['charset'])) {
  81. $sql = "SET NAMES '" . $this->_config['charset'] . "'";
  82. $this->_connection->exec($sql);
  83. }
  84. }
  85. /**
  86. * Returns a list of the tables in the database.
  87. *
  88. * @return array
  89. */
  90. public function listTables()
  91. {
  92. // @todo use a better query with joins instead of subqueries
  93. $sql = "SELECT c.relname AS table_name "
  94. . "FROM pg_class c, pg_user u "
  95. . "WHERE c.relowner = u.usesysid AND c.relkind = 'r' "
  96. . "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
  97. . "AND c.relname !~ '^(pg_|sql_)' "
  98. . "UNION "
  99. . "SELECT c.relname AS table_name "
  100. . "FROM pg_class c "
  101. . "WHERE c.relkind = 'r' "
  102. . "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
  103. . "AND NOT EXISTS (SELECT 1 FROM pg_user WHERE usesysid = c.relowner) "
  104. . "AND c.relname !~ '^pg_'";
  105. return $this->fetchCol($sql);
  106. }
  107. /**
  108. * Returns the column descriptions for a table.
  109. *
  110. * The return value is an associative array keyed by the column name,
  111. * as returned by the RDBMS.
  112. *
  113. * The value of each array element is an associative array
  114. * with the following keys:
  115. *
  116. * SCHEMA_NAME => string; name of database or schema
  117. * TABLE_NAME => string;
  118. * COLUMN_NAME => string; column name
  119. * COLUMN_POSITION => number; ordinal position of column in table
  120. * DATA_TYPE => string; SQL datatype name of column
  121. * DEFAULT => string; default expression of column, null if none
  122. * NULLABLE => boolean; true if column can have nulls
  123. * LENGTH => number; length of CHAR/VARCHAR
  124. * SCALE => number; scale of NUMERIC/DECIMAL
  125. * PRECISION => number; precision of NUMERIC/DECIMAL
  126. * UNSIGNED => boolean; unsigned property of an integer type
  127. * PRIMARY => boolean; true if column is part of the primary key
  128. * PRIMARY_POSITION => integer; position of column in primary key
  129. * IDENTITY => integer; true if column is auto-generated with unique values
  130. *
  131. * @todo Discover integer unsigned property.
  132. *
  133. * @param string $tableName
  134. * @param string $schemaName OPTIONAL
  135. * @return array
  136. */
  137. public function describeTable($tableName, $schemaName = null)
  138. {
  139. $sql = "SELECT
  140. a.attnum,
  141. n.nspname,
  142. c.relname,
  143. a.attname AS colname,
  144. t.typname AS type,
  145. a.atttypmod,
  146. FORMAT_TYPE(a.atttypid, a.atttypmod) AS complete_type,
  147. d.adsrc AS default_value,
  148. a.attnotnull AS notnull,
  149. a.attlen AS length,
  150. co.contype,
  151. ARRAY_TO_STRING(co.conkey, ',') AS conkey
  152. FROM pg_attribute AS a
  153. JOIN pg_class AS c ON a.attrelid = c.oid
  154. JOIN pg_namespace AS n ON c.relnamespace = n.oid
  155. JOIN pg_type AS t ON a.atttypid = t.oid
  156. LEFT OUTER JOIN pg_constraint AS co ON (co.conrelid = c.oid
  157. AND a.attnum = ANY(co.conkey) AND co.contype = 'p')
  158. LEFT OUTER JOIN pg_attrdef AS d ON d.adrelid = c.oid AND d.adnum = a.attnum
  159. WHERE a.attnum > 0 AND c.relname = ".$this->quote($tableName);
  160. if ($schemaName) {
  161. $sql .= " AND n.nspname = ".$this->quote($schemaName);
  162. }
  163. $sql .= ' ORDER BY a.attnum';
  164. $stmt = $this->query($sql);
  165. // Use FETCH_NUM so we are not dependent on the CASE attribute of the PDO connection
  166. $result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
  167. $attnum = 0;
  168. $nspname = 1;
  169. $relname = 2;
  170. $colname = 3;
  171. $type = 4;
  172. $atttypemod = 5;
  173. $complete_type = 6;
  174. $default_value = 7;
  175. $notnull = 8;
  176. $length = 9;
  177. $contype = 10;
  178. $conkey = 11;
  179. $desc = array();
  180. foreach ($result as $key => $row) {
  181. if ($row[$type] == 'varchar') {
  182. if (preg_match('/character varying(?:\((\d+)\))?/', $row[$complete_type], $matches)) {
  183. if (isset($matches[1])) {
  184. $row[$length] = $matches[1];
  185. } else {
  186. $row[$length] = null; // unlimited
  187. }
  188. }
  189. }
  190. list($primary, $primaryPosition, $identity) = array(false, null, false);
  191. if ($row[$contype] == 'p') {
  192. $primary = true;
  193. $primaryPosition = array_search($row[$attnum], explode(',', $row[$conkey])) + 1;
  194. $identity = (bool) (preg_match('/^nextval/', $row[$default_value]));
  195. }
  196. $desc[$this->foldCase($row[$colname])] = array(
  197. 'SCHEMA_NAME' => $this->foldCase($row[$nspname]),
  198. 'TABLE_NAME' => $this->foldCase($row[$relname]),
  199. 'COLUMN_NAME' => $this->foldCase($row[$colname]),
  200. 'COLUMN_POSITION' => $row[$attnum],
  201. 'DATA_TYPE' => $row[$type],
  202. 'DEFAULT' => $row[$default_value],
  203. 'NULLABLE' => (bool) ($row[$notnull] != 't'),
  204. 'LENGTH' => $row[$length],
  205. 'SCALE' => null, // @todo
  206. 'PRECISION' => null, // @todo
  207. 'UNSIGNED' => null, // @todo
  208. 'PRIMARY' => $primary,
  209. 'PRIMARY_POSITION' => $primaryPosition,
  210. 'IDENTITY' => $identity
  211. );
  212. }
  213. return $desc;
  214. }
  215. /**
  216. * Adds an adapter-specific LIMIT clause to the SELECT statement.
  217. *
  218. * @param string $sql
  219. * @param integer $count
  220. * @param integer $offset OPTIONAL
  221. * @return string
  222. */
  223. public function limit($sql, $count, $offset = 0)
  224. {
  225. $count = intval($count);
  226. if ($count <= 0) {
  227. /**
  228. * @see Zend_Db_Adapter_Exception
  229. */
  230. require_once 'Zend/Db/Adapter/Exception.php';
  231. throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid");
  232. }
  233. $offset = intval($offset);
  234. if ($offset < 0) {
  235. /**
  236. * @see Zend_Db_Adapter_Exception
  237. */
  238. require_once 'Zend/Db/Adapter/Exception.php';
  239. throw new Zend_Db_Adapter_Exception("LIMIT argument offset=$offset is not valid");
  240. }
  241. $sql .= " LIMIT $count";
  242. if ($offset > 0) {
  243. $sql .= " OFFSET $offset";
  244. }
  245. return $sql;
  246. }
  247. /**
  248. * Return the most recent value from the specified sequence in the database.
  249. * This is supported only on RDBMS brands that support sequences
  250. * (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null.
  251. *
  252. * @param string $sequenceName
  253. * @return string
  254. */
  255. public function lastSequenceId($sequenceName)
  256. {
  257. $this->_connect();
  258. $value = $this->fetchOne("SELECT CURRVAL(".$this->quote($sequenceName).")");
  259. return $value;
  260. }
  261. /**
  262. * Generate a new value from the specified sequence in the database, and return it.
  263. * This is supported only on RDBMS brands that support sequences
  264. * (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null.
  265. *
  266. * @param string $sequenceName
  267. * @return string
  268. */
  269. public function nextSequenceId($sequenceName)
  270. {
  271. $this->_connect();
  272. $value = $this->fetchOne("SELECT NEXTVAL(".$this->quote($sequenceName).")");
  273. return $value;
  274. }
  275. /**
  276. * Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
  277. *
  278. * As a convention, on RDBMS brands that support sequences
  279. * (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence
  280. * from the arguments and returns the last id generated by that sequence.
  281. * On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
  282. * returns the last value generated for such a column, and the table name
  283. * argument is disregarded.
  284. *
  285. * @param string $tableName OPTIONAL Name of table.
  286. * @param string $primaryKey OPTIONAL Name of primary key column.
  287. * @return string
  288. */
  289. public function lastInsertId($tableName = null, $primaryKey = null)
  290. {
  291. if ($tableName !== null) {
  292. $sequenceName = $tableName;
  293. if ($primaryKey) {
  294. $sequenceName .= "_$primaryKey";
  295. }
  296. $sequenceName .= '_seq';
  297. return $this->lastSequenceId($sequenceName);
  298. }
  299. return $this->_connection->lastInsertId($tableName);
  300. }
  301. }