PageRenderTime 44ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/library/Zend/Db/Adapter/Pdo/Mssql.php

https://bitbucket.org/openfisma-ondemand/openfisma
PHP | 423 lines | 226 code | 37 blank | 160 comment | 26 complexity | bec8a9c1426c43375802c11fcabd2577 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-2.1, GPL-3.0, Apache-2.0, EPL-1.0
  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-2011 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 Microsoft SQL Server databases and performing common operations.
  28. *
  29. * @category Zend
  30. * @package Zend_Db
  31. * @subpackage Adapter
  32. * @copyright Copyright (c) 2005-2011 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_Mssql extends Zend_Db_Adapter_Pdo_Abstract
  36. {
  37. /**
  38. * PDO type.
  39. *
  40. * @var string
  41. */
  42. protected $_pdoType = 'mssql';
  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. 'INT' => Zend_Db::INT_TYPE,
  59. 'SMALLINT' => Zend_Db::INT_TYPE,
  60. 'TINYINT' => Zend_Db::INT_TYPE,
  61. 'BIGINT' => Zend_Db::BIGINT_TYPE,
  62. 'DECIMAL' => Zend_Db::FLOAT_TYPE,
  63. 'FLOAT' => Zend_Db::FLOAT_TYPE,
  64. 'MONEY' => Zend_Db::FLOAT_TYPE,
  65. 'NUMERIC' => Zend_Db::FLOAT_TYPE,
  66. 'REAL' => Zend_Db::FLOAT_TYPE,
  67. 'SMALLMONEY' => Zend_Db::FLOAT_TYPE
  68. );
  69. /**
  70. * Creates a PDO DSN for the adapter from $this->_config settings.
  71. *
  72. * @return string
  73. */
  74. protected function _dsn()
  75. {
  76. // baseline of DSN parts
  77. $dsn = $this->_config;
  78. // don't pass the username and password in the DSN
  79. unset($dsn['username']);
  80. unset($dsn['password']);
  81. unset($dsn['options']);
  82. unset($dsn['persistent']);
  83. unset($dsn['driver_options']);
  84. if (isset($dsn['port'])) {
  85. $seperator = ':';
  86. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  87. $seperator = ',';
  88. }
  89. $dsn['host'] .= $seperator . $dsn['port'];
  90. unset($dsn['port']);
  91. }
  92. // this driver supports multiple DSN prefixes
  93. // @see http://www.php.net/manual/en/ref.pdo-dblib.connection.php
  94. if (isset($dsn['pdoType'])) {
  95. switch (strtolower($dsn['pdoType'])) {
  96. case 'freetds':
  97. case 'sybase':
  98. $this->_pdoType = 'sybase';
  99. break;
  100. case 'mssql':
  101. $this->_pdoType = 'mssql';
  102. break;
  103. case 'dblib':
  104. default:
  105. $this->_pdoType = 'dblib';
  106. break;
  107. }
  108. unset($dsn['pdoType']);
  109. }
  110. // use all remaining parts in the DSN
  111. foreach ($dsn as $key => $val) {
  112. $dsn[$key] = "$key=$val";
  113. }
  114. $dsn = $this->_pdoType . ':' . implode(';', $dsn);
  115. return $dsn;
  116. }
  117. /**
  118. * @return void
  119. */
  120. protected function _connect()
  121. {
  122. if ($this->_connection) {
  123. return;
  124. }
  125. parent::_connect();
  126. $this->_connection->exec('SET QUOTED_IDENTIFIER ON');
  127. }
  128. /**
  129. * Begin a transaction.
  130. *
  131. * It is necessary to override the abstract PDO transaction functions here, as
  132. * the PDO driver for MSSQL does not support transactions.
  133. */
  134. protected function _beginTransaction()
  135. {
  136. $this->_connect();
  137. $this->_connection->exec('BEGIN TRANSACTION');
  138. return true;
  139. }
  140. /**
  141. * Commit a transaction.
  142. *
  143. * It is necessary to override the abstract PDO transaction functions here, as
  144. * the PDO driver for MSSQL does not support transactions.
  145. */
  146. protected function _commit()
  147. {
  148. $this->_connect();
  149. $this->_connection->exec('COMMIT TRANSACTION');
  150. return true;
  151. }
  152. /**
  153. * Roll-back a transaction.
  154. *
  155. * It is necessary to override the abstract PDO transaction functions here, as
  156. * the PDO driver for MSSQL does not support transactions.
  157. */
  158. protected function _rollBack() {
  159. $this->_connect();
  160. $this->_connection->exec('ROLLBACK TRANSACTION');
  161. return true;
  162. }
  163. /**
  164. * Returns a list of the tables in the database.
  165. *
  166. * @return array
  167. */
  168. public function listTables()
  169. {
  170. $sql = "SELECT name FROM sysobjects WHERE type = 'U' ORDER BY name";
  171. return $this->fetchCol($sql);
  172. }
  173. /**
  174. * Returns the column descriptions for a table.
  175. *
  176. * The return value is an associative array keyed by the column name,
  177. * as returned by the RDBMS.
  178. *
  179. * The value of each array element is an associative array
  180. * with the following keys:
  181. *
  182. * SCHEMA_NAME => string; name of database or schema
  183. * TABLE_NAME => string;
  184. * COLUMN_NAME => string; column name
  185. * COLUMN_POSITION => number; ordinal position of column in table
  186. * DATA_TYPE => string; SQL datatype name of column
  187. * DEFAULT => string; default expression of column, null if none
  188. * NULLABLE => boolean; true if column can have nulls
  189. * LENGTH => number; length of CHAR/VARCHAR
  190. * SCALE => number; scale of NUMERIC/DECIMAL
  191. * PRECISION => number; precision of NUMERIC/DECIMAL
  192. * UNSIGNED => boolean; unsigned property of an integer type
  193. * PRIMARY => boolean; true if column is part of the primary key
  194. * PRIMARY_POSITION => integer; position of column in primary key
  195. * PRIMARY_AUTO => integer; position of auto-generated column in primary key
  196. *
  197. * @todo Discover column primary key position.
  198. * @todo Discover integer unsigned property.
  199. *
  200. * @param string $tableName
  201. * @param string $schemaName OPTIONAL
  202. * @return array
  203. */
  204. public function describeTable($tableName, $schemaName = null)
  205. {
  206. if ($schemaName != null) {
  207. if (strpos($schemaName, '.') !== false) {
  208. $result = explode('.', $schemaName);
  209. $schemaName = $result[1];
  210. }
  211. }
  212. /**
  213. * Discover metadata information about this table.
  214. */
  215. $sql = "exec sp_columns @table_name = " . $this->quoteIdentifier($tableName, true);
  216. if ($schemaName != null) {
  217. $sql .= ", @table_owner = " . $this->quoteIdentifier($schemaName, true);
  218. }
  219. $stmt = $this->query($sql);
  220. $result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
  221. $table_name = 2;
  222. $column_name = 3;
  223. $type_name = 5;
  224. $precision = 6;
  225. $length = 7;
  226. $scale = 8;
  227. $nullable = 10;
  228. $column_def = 12;
  229. $column_position = 16;
  230. /**
  231. * Discover primary key column(s) for this table.
  232. */
  233. $sql = "exec sp_pkeys @table_name = " . $this->quoteIdentifier($tableName, true);
  234. if ($schemaName != null) {
  235. $sql .= ", @table_owner = " . $this->quoteIdentifier($schemaName, true);
  236. }
  237. $stmt = $this->query($sql);
  238. $primaryKeysResult = $stmt->fetchAll(Zend_Db::FETCH_NUM);
  239. $primaryKeyColumn = array();
  240. $pkey_column_name = 3;
  241. $pkey_key_seq = 4;
  242. foreach ($primaryKeysResult as $pkeysRow) {
  243. $primaryKeyColumn[$pkeysRow[$pkey_column_name]] = $pkeysRow[$pkey_key_seq];
  244. }
  245. $desc = array();
  246. $p = 1;
  247. foreach ($result as $key => $row) {
  248. $identity = false;
  249. $words = explode(' ', $row[$type_name], 2);
  250. if (isset($words[0])) {
  251. $type = $words[0];
  252. if (isset($words[1])) {
  253. $identity = (bool) preg_match('/identity/', $words[1]);
  254. }
  255. }
  256. $isPrimary = array_key_exists($row[$column_name], $primaryKeyColumn);
  257. if ($isPrimary) {
  258. $primaryPosition = $primaryKeyColumn[$row[$column_name]];
  259. } else {
  260. $primaryPosition = null;
  261. }
  262. $desc[$this->foldCase($row[$column_name])] = array(
  263. 'SCHEMA_NAME' => null, // @todo
  264. 'TABLE_NAME' => $this->foldCase($row[$table_name]),
  265. 'COLUMN_NAME' => $this->foldCase($row[$column_name]),
  266. 'COLUMN_POSITION' => (int) $row[$column_position],
  267. 'DATA_TYPE' => $type,
  268. 'DEFAULT' => $row[$column_def],
  269. 'NULLABLE' => (bool) $row[$nullable],
  270. 'LENGTH' => $row[$length],
  271. 'SCALE' => $row[$scale],
  272. 'PRECISION' => $row[$precision],
  273. 'UNSIGNED' => null, // @todo
  274. 'PRIMARY' => $isPrimary,
  275. 'PRIMARY_POSITION' => $primaryPosition,
  276. 'IDENTITY' => $identity
  277. );
  278. }
  279. return $desc;
  280. }
  281. /**
  282. * Adds an adapter-specific LIMIT clause to the SELECT statement.
  283. *
  284. * @link http://lists.bestpractical.com/pipermail/rt-devel/2005-June/007339.html
  285. *
  286. * @param string $sql
  287. * @param integer $count
  288. * @param integer $offset OPTIONAL
  289. * @throws Zend_Db_Adapter_Exception
  290. * @return string
  291. */
  292. public function limit($sql, $count, $offset = 0)
  293. {
  294. $count = intval($count);
  295. if ($count <= 0) {
  296. /** @see Zend_Db_Adapter_Exception */
  297. // require_once 'Zend/Db/Adapter/Exception.php';
  298. throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid");
  299. }
  300. $offset = intval($offset);
  301. if ($offset < 0) {
  302. /** @see Zend_Db_Adapter_Exception */
  303. // require_once 'Zend/Db/Adapter/Exception.php';
  304. throw new Zend_Db_Adapter_Exception("LIMIT argument offset=$offset is not valid");
  305. }
  306. $sql = preg_replace(
  307. '/^SELECT\s+(DISTINCT\s)?/i',
  308. 'SELECT $1TOP ' . ($count+$offset) . ' ',
  309. $sql
  310. );
  311. if ($offset > 0) {
  312. $orderby = stristr($sql, 'ORDER BY');
  313. if ($orderby !== false) {
  314. $orderParts = explode(',', substr($orderby, 8));
  315. $pregReplaceCount = null;
  316. $orderbyInverseParts = array();
  317. foreach ($orderParts as $orderPart) {
  318. $orderPart = rtrim($orderPart);
  319. $inv = preg_replace('/\s+desc$/i', ' ASC', $orderPart, 1, $pregReplaceCount);
  320. if ($pregReplaceCount) {
  321. $orderbyInverseParts[] = $inv;
  322. continue;
  323. }
  324. $inv = preg_replace('/\s+asc$/i', ' DESC', $orderPart, 1, $pregReplaceCount);
  325. if ($pregReplaceCount) {
  326. $orderbyInverseParts[] = $inv;
  327. continue;
  328. } else {
  329. $orderbyInverseParts[] = $orderPart . ' DESC';
  330. }
  331. }
  332. $orderbyInverse = 'ORDER BY ' . implode(', ', $orderbyInverseParts);
  333. }
  334. $sql = 'SELECT * FROM (SELECT TOP ' . $count . ' * FROM (' . $sql . ') AS inner_tbl';
  335. if ($orderby !== false) {
  336. $sql .= ' ' . $orderbyInverse . ' ';
  337. }
  338. $sql .= ') AS outer_tbl';
  339. if ($orderby !== false) {
  340. $sql .= ' ' . $orderby;
  341. }
  342. }
  343. return $sql;
  344. }
  345. /**
  346. * Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
  347. *
  348. * As a convention, on RDBMS brands that support sequences
  349. * (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence
  350. * from the arguments and returns the last id generated by that sequence.
  351. * On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
  352. * returns the last value generated for such a column, and the table name
  353. * argument is disregarded.
  354. *
  355. * Microsoft SQL Server does not support sequences, so the arguments to
  356. * this method are ignored.
  357. *
  358. * @param string $tableName OPTIONAL Name of table.
  359. * @param string $primaryKey OPTIONAL Name of primary key column.
  360. * @return string
  361. * @throws Zend_Db_Adapter_Exception
  362. */
  363. public function lastInsertId($tableName = null, $primaryKey = null)
  364. {
  365. $sql = 'SELECT SCOPE_IDENTITY()';
  366. return (int)$this->fetchOne($sql);
  367. }
  368. /**
  369. * Retrieve server version in PHP style
  370. * Pdo_Mssql doesn't support getAttribute(PDO::ATTR_SERVER_VERSION)
  371. * @return string
  372. */
  373. public function getServerVersion()
  374. {
  375. try {
  376. $stmt = $this->query("SELECT SERVERPROPERTY('productversion')");
  377. $result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
  378. if (count($result)) {
  379. return $result[0][0];
  380. }
  381. return null;
  382. } catch (PDOException $e) {
  383. return null;
  384. }
  385. }
  386. }