PageRenderTime 104ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

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

http://github.com/zendframework/zf2
PHP | 421 lines | 229 code | 35 blank | 157 comment | 26 complexity | 127f65432fc09a71550944eb63ba343d MD5 | raw file
Possible License(s): BSD-3-Clause
  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-2012 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. */
  21. /**
  22. * @namespace
  23. */
  24. namespace Zend\Db\Adapter\Pdo;
  25. use Zend\Db;
  26. use Zend\Db\Adapter;
  27. /**
  28. * Class for connecting to Microsoft SQL Server databases and performing common operations.
  29. *
  30. * @uses \Zend\Db\Db
  31. * @uses \Zend\Db\Adapter\Exception
  32. * @uses \Zend\Db\Adapter\Pdo\AbstractPdo
  33. * @category Zend
  34. * @package Zend_Db
  35. * @subpackage Adapter
  36. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  37. * @license http://framework.zend.com/license/new-bsd New BSD License
  38. */
  39. class Mssql extends \Zend\Db\Adapter\AbstractPdoAdapter
  40. {
  41. /**
  42. * Pdo type.
  43. *
  44. * @var string
  45. */
  46. protected $_pdoType = 'mssql';
  47. /**
  48. * Keys are UPPERCASE SQL datatypes or the constants
  49. * Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
  50. *
  51. * Values are:
  52. * 0 = 32-bit integer
  53. * 1 = 64-bit integer
  54. * 2 = float or decimal
  55. *
  56. * @var array Associative array of datatypes to values 0, 1, or 2.
  57. */
  58. protected $_numericDataTypes = array(
  59. Db\Db::INT_TYPE => Db\Db::INT_TYPE,
  60. Db\Db::BIGINT_TYPE => Db\Db::BIGINT_TYPE,
  61. Db\Db::FLOAT_TYPE => Db\Db::FLOAT_TYPE,
  62. 'INT' => Db\Db::INT_TYPE,
  63. 'SMALLINT' => Db\Db::INT_TYPE,
  64. 'TINYINT' => Db\Db::INT_TYPE,
  65. 'BIGINT' => Db\Db::BIGINT_TYPE,
  66. 'DECIMAL' => Db\Db::FLOAT_TYPE,
  67. 'FLOAT' => Db\Db::FLOAT_TYPE,
  68. 'MONEY' => Db\Db::FLOAT_TYPE,
  69. 'NUMERIC' => Db\Db::FLOAT_TYPE,
  70. 'REAL' => Db\Db::FLOAT_TYPE,
  71. 'SMALLMONEY' => Db\Db::FLOAT_TYPE
  72. );
  73. /**
  74. * Creates a Pdo DSN for the adapter from $this->_config settings.
  75. *
  76. * @return string
  77. */
  78. protected function _dsn()
  79. {
  80. // baseline of DSN parts
  81. $dsn = $this->_config;
  82. // don't pass the username and password in the DSN
  83. unset($dsn['username']);
  84. unset($dsn['password']);
  85. unset($dsn['options']);
  86. unset($dsn['persistent']);
  87. unset($dsn['driver_options']);
  88. if (isset($dsn['port'])) {
  89. $seperator = ':';
  90. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  91. $seperator = ',';
  92. }
  93. $dsn['host'] .= $seperator . $dsn['port'];
  94. unset($dsn['port']);
  95. }
  96. // this driver supports multiple DSN prefixes
  97. // @see http://www.php.net/manual/en/ref.pdo-dblib.connection.php
  98. if (isset($dsn['pdoType'])) {
  99. switch (strtolower($dsn['pdoType'])) {
  100. case 'freetds':
  101. case 'sybase':
  102. $this->_pdoType = 'sybase';
  103. break;
  104. case 'mssql':
  105. $this->_pdoType = 'mssql';
  106. break;
  107. case 'dblib':
  108. default:
  109. $this->_pdoType = 'dblib';
  110. break;
  111. }
  112. unset($dsn['pdoType']);
  113. }
  114. // use all remaining parts in the DSN
  115. foreach ($dsn as $key => $val) {
  116. $dsn[$key] = "$key=$val";
  117. }
  118. $dsn = $this->_pdoType . ':' . implode(';', $dsn);
  119. return $dsn;
  120. }
  121. /**
  122. * @return void
  123. */
  124. protected function _connect()
  125. {
  126. if ($this->_connection) {
  127. return;
  128. }
  129. parent::_connect();
  130. $this->_connection->exec('SET QUOTED_IDENTIFIER ON');
  131. }
  132. /**
  133. * Begin a transaction.
  134. *
  135. * It is necessary to override the abstract Pdo transaction functions here, as
  136. * the Pdo driver for Mssql does not support transactions.
  137. */
  138. protected function _beginTransaction()
  139. {
  140. $this->_connect();
  141. $this->_connection->exec('BEGIN TRANSACTION');
  142. return true;
  143. }
  144. /**
  145. * Commit a transaction.
  146. *
  147. * It is necessary to override the abstract Pdo transaction functions here, as
  148. * the Pdo driver for Mssql does not support transactions.
  149. */
  150. protected function _commit()
  151. {
  152. $this->_connect();
  153. $this->_connection->exec('COMMIT TRANSACTION');
  154. return true;
  155. }
  156. /**
  157. * Roll-back a transaction.
  158. *
  159. * It is necessary to override the abstract Pdo transaction functions here, as
  160. * the Pdo driver for Mssql does not support transactions.
  161. */
  162. protected function _rollBack() {
  163. $this->_connect();
  164. $this->_connection->exec('ROLLBACK TRANSACTION');
  165. return true;
  166. }
  167. /**
  168. * Returns a list of the tables in the database.
  169. *
  170. * @return array
  171. */
  172. public function listTables()
  173. {
  174. $sql = "SELECT name FROM sysobjects WHERE type = 'U' ORDER BY name";
  175. return $this->fetchCol($sql);
  176. }
  177. /**
  178. * Returns the column descriptions for a table.
  179. *
  180. * The return value is an associative array keyed by the column name,
  181. * as returned by the RDBMS.
  182. *
  183. * The value of each array element is an associative array
  184. * with the following keys:
  185. *
  186. * SCHEMA_NAME => string; name of database or schema
  187. * TABLE_NAME => string;
  188. * COLUMN_NAME => string; column name
  189. * COLUMN_POSITION => number; ordinal position of column in table
  190. * DATA_TYPE => string; SQL datatype name of column
  191. * DEFAULT => string; default expression of column, null if none
  192. * NULLABLE => boolean; true if column can have nulls
  193. * LENGTH => number; length of CHAR/VARCHAR
  194. * SCALE => number; scale of NUMERIC/DECIMAL
  195. * PRECISION => number; precision of NUMERIC/DECIMAL
  196. * UNSIGNED => boolean; unsigned property of an integer type
  197. * PRIMARY => boolean; true if column is part of the primary key
  198. * PRIMARY_POSITION => integer; position of column in primary key
  199. * PRIMARY_AUTO => integer; position of auto-generated column in primary key
  200. *
  201. * @todo Discover column primary key position.
  202. * @todo Discover integer unsigned property.
  203. *
  204. * @param string $tableName
  205. * @param string $schemaName OPTIONAL
  206. * @return array
  207. */
  208. public function describeTable($tableName, $schemaName = null)
  209. {
  210. if ($schemaName != null) {
  211. if (strpos($schemaName, '.') !== false) {
  212. $result = explode('.', $schemaName);
  213. $schemaName = $result[1];
  214. }
  215. }
  216. /**
  217. * Discover metadata information about this table.
  218. */
  219. $sql = "exec sp_columns @table_name = " . $this->quoteIdentifier($tableName, true);
  220. if ($schemaName != null) {
  221. $sql .= ", @table_owner = " . $this->quoteIdentifier($schemaName, true);
  222. }
  223. $stmt = $this->query($sql);
  224. $result = $stmt->fetchAll(Db\Db::FETCH_NUM);
  225. $table_name = 2;
  226. $column_name = 3;
  227. $type_name = 5;
  228. $precision = 6;
  229. $length = 7;
  230. $scale = 8;
  231. $nullable = 10;
  232. $column_def = 12;
  233. $column_position = 16;
  234. /**
  235. * Discover primary key column(s) for this table.
  236. */
  237. $sql = "exec sp_pkeys @table_name = " . $this->quoteIdentifier($tableName, true);
  238. if ($schemaName != null) {
  239. $sql .= ", @table_owner = " . $this->quoteIdentifier($schemaName, true);
  240. }
  241. $stmt = $this->query($sql);
  242. $primaryKeysResult = $stmt->fetchAll(Db\Db::FETCH_NUM);
  243. $primaryKeyColumn = array();
  244. $pkey_column_name = 3;
  245. $pkey_key_seq = 4;
  246. foreach ($primaryKeysResult as $pkeysRow) {
  247. $primaryKeyColumn[$pkeysRow[$pkey_column_name]] = $pkeysRow[$pkey_key_seq];
  248. }
  249. $desc = array();
  250. $p = 1;
  251. foreach ($result as $key => $row) {
  252. $identity = false;
  253. $words = explode(' ', $row[$type_name], 2);
  254. if (isset($words[0])) {
  255. $type = $words[0];
  256. if (isset($words[1])) {
  257. $identity = (bool) preg_match('/identity/', $words[1]);
  258. }
  259. }
  260. $isPrimary = array_key_exists($row[$column_name], $primaryKeyColumn);
  261. if ($isPrimary) {
  262. $primaryPosition = $primaryKeyColumn[$row[$column_name]];
  263. } else {
  264. $primaryPosition = null;
  265. }
  266. $desc[$this->foldCase($row[$column_name])] = array(
  267. 'SCHEMA_NAME' => null, // @todo
  268. 'TABLE_NAME' => $this->foldCase($row[$table_name]),
  269. 'COLUMN_NAME' => $this->foldCase($row[$column_name]),
  270. 'COLUMN_POSITION' => (int) $row[$column_position],
  271. 'DATA_TYPE' => $type,
  272. 'DEFAULT' => $row[$column_def],
  273. 'NULLABLE' => (bool) $row[$nullable],
  274. 'LENGTH' => $row[$length],
  275. 'SCALE' => $row[$scale],
  276. 'PRECISION' => $row[$precision],
  277. 'UNSIGNED' => null, // @todo
  278. 'PRIMARY' => $isPrimary,
  279. 'PRIMARY_POSITION' => $primaryPosition,
  280. 'IDENTITY' => $identity
  281. );
  282. }
  283. return $desc;
  284. }
  285. /**
  286. * Adds an adapter-specific LIMIT clause to the SELECT statement.
  287. *
  288. * @link http://lists.bestpractical.com/pipermail/rt-devel/2005-June/007339.html
  289. *
  290. * @param string $sql
  291. * @param integer $count
  292. * @param integer $offset OPTIONAL
  293. * @throws \Zend\Db\Adapter\Exception
  294. * @return string
  295. */
  296. public function limit($sql, $count, $offset = 0)
  297. {
  298. $count = intval($count);
  299. if ($count <= 0) {
  300. throw new Adapter\Exception("LIMIT argument count=$count is not valid");
  301. }
  302. $offset = intval($offset);
  303. if ($offset < 0) {
  304. throw new 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(Db\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. }