Mssql.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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-2009 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-2009 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. /**
  207. * Discover metadata information about this table.
  208. */
  209. $sql = "exec sp_columns @table_name = " . $this->quoteIdentifier($tableName, true);
  210. $stmt = $this->query($sql);
  211. $result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
  212. $table_name = 2;
  213. $column_name = 3;
  214. $type_name = 5;
  215. $precision = 6;
  216. $length = 7;
  217. $scale = 8;
  218. $nullable = 10;
  219. $column_def = 12;
  220. $column_position = 16;
  221. /**
  222. * Discover primary key column(s) for this table.
  223. */
  224. $sql = "exec sp_pkeys @table_name = " . $this->quoteIdentifier($tableName, true);
  225. $stmt = $this->query($sql);
  226. $primaryKeysResult = $stmt->fetchAll(Zend_Db::FETCH_NUM);
  227. $primaryKeyColumn = array();
  228. $pkey_column_name = 3;
  229. $pkey_key_seq = 4;
  230. foreach ($primaryKeysResult as $pkeysRow) {
  231. $primaryKeyColumn[$pkeysRow[$pkey_column_name]] = $pkeysRow[$pkey_key_seq];
  232. }
  233. $desc = array();
  234. $p = 1;
  235. foreach ($result as $key => $row) {
  236. $identity = false;
  237. $words = explode(' ', $row[$type_name], 2);
  238. if (isset($words[0])) {
  239. $type = $words[0];
  240. if (isset($words[1])) {
  241. $identity = (bool) preg_match('/identity/', $words[1]);
  242. }
  243. }
  244. $isPrimary = array_key_exists($row[$column_name], $primaryKeyColumn);
  245. if ($isPrimary) {
  246. $primaryPosition = $primaryKeyColumn[$row[$column_name]];
  247. } else {
  248. $primaryPosition = null;
  249. }
  250. $desc[$this->foldCase($row[$column_name])] = array(
  251. 'SCHEMA_NAME' => null, // @todo
  252. 'TABLE_NAME' => $this->foldCase($row[$table_name]),
  253. 'COLUMN_NAME' => $this->foldCase($row[$column_name]),
  254. 'COLUMN_POSITION' => (int) $row[$column_position],
  255. 'DATA_TYPE' => $type,
  256. 'DEFAULT' => $row[$column_def],
  257. 'NULLABLE' => (bool) $row[$nullable],
  258. 'LENGTH' => $row[$length],
  259. 'SCALE' => $row[$scale],
  260. 'PRECISION' => $row[$precision],
  261. 'UNSIGNED' => null, // @todo
  262. 'PRIMARY' => $isPrimary,
  263. 'PRIMARY_POSITION' => $primaryPosition,
  264. 'IDENTITY' => $identity
  265. );
  266. }
  267. return $desc;
  268. }
  269. /**
  270. * Adds an adapter-specific LIMIT clause to the SELECT statement.
  271. *
  272. * @link http://lists.bestpractical.com/pipermail/rt-devel/2005-June/007339.html
  273. *
  274. * @param string $sql
  275. * @param integer $count
  276. * @param integer $offset OPTIONAL
  277. * @throws Zend_Db_Adapter_Exception
  278. * @return string
  279. */
  280. public function limit($sql, $count, $offset = 0)
  281. {
  282. $count = intval($count);
  283. if ($count <= 0) {
  284. /** @see Zend_Db_Adapter_Exception */
  285. require_once 'Zend/Db/Adapter/Exception.php';
  286. throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid");
  287. }
  288. $offset = intval($offset);
  289. if ($offset < 0) {
  290. /** @see Zend_Db_Adapter_Exception */
  291. require_once 'Zend/Db/Adapter/Exception.php';
  292. throw new Zend_Db_Adapter_Exception("LIMIT argument offset=$offset is not valid");
  293. }
  294. $sql = preg_replace(
  295. '/^SELECT\s+(DISTINCT\s)?/i',
  296. 'SELECT $1TOP ' . ($count+$offset) . ' ',
  297. $sql
  298. );
  299. if ($offset > 0) {
  300. $orderby = stristr($sql, 'ORDER BY');
  301. if ($orderby !== false) {
  302. $orderParts = explode(',', substr($orderby, 8));
  303. $pregReplaceCount = null;
  304. $orderbyInverseParts = array();
  305. foreach ($orderParts as $orderPart) {
  306. $orderPart = rtrim($orderPart);
  307. $inv = preg_replace('/\s+desc$/i', ' ASC', $orderPart, 1, $pregReplaceCount);
  308. if ($pregReplaceCount) {
  309. $orderbyInverseParts[] = $inv;
  310. continue;
  311. }
  312. $inv = preg_replace('/\s+asc$/i', ' DESC', $orderPart, 1, $pregReplaceCount);
  313. if ($pregReplaceCount) {
  314. $orderbyInverseParts[] = $inv;
  315. continue;
  316. } else {
  317. $orderbyInverseParts[] = $orderPart . ' DESC';
  318. }
  319. }
  320. $orderbyInverse = 'ORDER BY ' . implode(', ', $orderbyInverseParts);
  321. }
  322. $sql = 'SELECT * FROM (SELECT TOP ' . $count . ' * FROM (' . $sql . ') AS inner_tbl';
  323. if ($orderby !== false) {
  324. $sql .= ' ' . $orderbyInverse . ' ';
  325. }
  326. $sql .= ') AS outer_tbl';
  327. if ($orderby !== false) {
  328. $sql .= ' ' . $orderby;
  329. }
  330. }
  331. return $sql;
  332. }
  333. /**
  334. * Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
  335. *
  336. * As a convention, on RDBMS brands that support sequences
  337. * (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence
  338. * from the arguments and returns the last id generated by that sequence.
  339. * On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
  340. * returns the last value generated for such a column, and the table name
  341. * argument is disregarded.
  342. *
  343. * Microsoft SQL Server does not support sequences, so the arguments to
  344. * this method are ignored.
  345. *
  346. * @param string $tableName OPTIONAL Name of table.
  347. * @param string $primaryKey OPTIONAL Name of primary key column.
  348. * @return string
  349. * @throws Zend_Db_Adapter_Exception
  350. */
  351. public function lastInsertId($tableName = null, $primaryKey = null)
  352. {
  353. $sql = 'SELECT SCOPE_IDENTITY()';
  354. return (int)$this->fetchOne($sql);
  355. }
  356. /**
  357. * Retrieve server version in PHP style
  358. * Pdo_Mssql doesn't support getAttribute(PDO::ATTR_SERVER_VERSION)
  359. * @return string
  360. */
  361. public function getServerVersion()
  362. {
  363. try {
  364. $stmt = $this->query("SELECT SERVERPROPERTY('productversion')");
  365. $result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
  366. if (count($result)) {
  367. return $result[0][0];
  368. }
  369. return null;
  370. } catch (PDOException $e) {
  371. return null;
  372. }
  373. }
  374. }