Sqlsrv.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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. */
  21. /**
  22. * @see Zend_Loader
  23. */
  24. require_once 'Zend/Loader.php';
  25. /**
  26. * @see Zend_Db_Adapter_Abstract
  27. */
  28. require_once 'Zend/Db/Adapter/Abstract.php';
  29. /**
  30. * @see Zend_Db_Statement_Sqlsrv
  31. */
  32. require_once 'Zend/Db/Statement/Sqlsrv.php';
  33. /**
  34. * @category Zend
  35. * @package Zend_Db
  36. * @subpackage Adapter
  37. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  38. * @license http://framework.zend.com/license/new-bsd New BSD License
  39. */
  40. class Zend_Db_Adapter_Sqlsrv extends Zend_Db_Adapter_Abstract
  41. {
  42. /**
  43. * User-provided configuration.
  44. *
  45. * Basic keys are:
  46. *
  47. * username => (string) Connect to the database as this username.
  48. * password => (string) Password associated with the username.
  49. * dbname => The name of the local SQL Server instance
  50. *
  51. * @var array
  52. */
  53. protected $_config = array(
  54. 'dbname' => null,
  55. 'username' => null,
  56. 'password' => null,
  57. );
  58. /**
  59. * Last insert id from INSERT query
  60. *
  61. * @var int
  62. */
  63. protected $_lastInsertId;
  64. /**
  65. * Query used to fetch last insert id
  66. *
  67. * @var string
  68. */
  69. protected $_lastInsertSQL = 'SELECT SCOPE_IDENTITY() as Current_Identity';
  70. /**
  71. * Keys are UPPERCASE SQL datatypes or the constants
  72. * Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
  73. *
  74. * Values are:
  75. * 0 = 32-bit integer
  76. * 1 = 64-bit integer
  77. * 2 = float or decimal
  78. *
  79. * @var array Associative array of datatypes to values 0, 1, or 2.
  80. */
  81. protected $_numericDataTypes = array(
  82. Zend_Db::INT_TYPE => Zend_Db::INT_TYPE,
  83. Zend_Db::BIGINT_TYPE => Zend_Db::BIGINT_TYPE,
  84. Zend_Db::FLOAT_TYPE => Zend_Db::FLOAT_TYPE,
  85. 'INT' => Zend_Db::INT_TYPE,
  86. 'SMALLINT' => Zend_Db::INT_TYPE,
  87. 'TINYINT' => Zend_Db::INT_TYPE,
  88. 'BIGINT' => Zend_Db::BIGINT_TYPE,
  89. 'DECIMAL' => Zend_Db::FLOAT_TYPE,
  90. 'FLOAT' => Zend_Db::FLOAT_TYPE,
  91. 'MONEY' => Zend_Db::FLOAT_TYPE,
  92. 'NUMERIC' => Zend_Db::FLOAT_TYPE,
  93. 'REAL' => Zend_Db::FLOAT_TYPE,
  94. 'SMALLMONEY' => Zend_Db::FLOAT_TYPE,
  95. );
  96. /**
  97. * Default class name for a DB statement.
  98. *
  99. * @var string
  100. */
  101. protected $_defaultStmtClass = 'Zend_Db_Statement_Sqlsrv';
  102. /**
  103. * Creates a connection resource.
  104. *
  105. * @return void
  106. * @throws Zend_Db_Adapter_Sqlsrv_Exception
  107. */
  108. protected function _connect()
  109. {
  110. if (is_resource($this->_connection)) {
  111. // connection already exists
  112. return;
  113. }
  114. if (!extension_loaded('sqlsrv')) {
  115. /**
  116. * @see Zend_Db_Adapter_Sqlsrv_Exception
  117. */
  118. require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
  119. throw new Zend_Db_Adapter_Sqlsrv_Exception('The Sqlsrv extension is required for this adapter but the extension is not loaded');
  120. }
  121. $serverName = $this->_config['host'];
  122. if (isset($this->_config['port'])) {
  123. $port = (integer) $this->_config['port'];
  124. $serverName .= ', ' . $port;
  125. }
  126. $connectionInfo = array(
  127. 'Database' => $this->_config['dbname'],
  128. 'UID' => $this->_config['username'],
  129. 'PWD' => $this->_config['password'],
  130. );
  131. if (!empty($this->_config['driver_options'])) {
  132. foreach ($this->_config['driver_options'] as $option => $value) {
  133. // A value may be a constant.
  134. if (is_string($value)) {
  135. $constantValue = @constant(strtoupper($value));
  136. if ($constantValue === null) {
  137. $connectionInfo[$option] = $value;
  138. } else {
  139. $connectionInfo[$option] = $constantValue;
  140. }
  141. }
  142. }
  143. }
  144. $this->_connection = sqlsrv_connect($serverName, $connectionInfo);
  145. if (!$this->_connection) {
  146. /**
  147. * @see Zend_Db_Adapter_Sqlsrv_Exception
  148. */
  149. require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
  150. throw new Zend_Db_Adapter_Sqlsrv_Exception(sqlsrv_errors());
  151. }
  152. sqlsrv_query($this->_connection, 'SET QUOTED_IDENTIFIER ON');
  153. }
  154. /**
  155. * Set the transaction isoltion level.
  156. *
  157. * @param integer|null $level A fetch mode from SQLSRV_TXN_*.
  158. * @return true
  159. * @throws Zend_Db_Adapter_Sqlsrv_Exception
  160. */
  161. public function setTransactionIsolationLevel($level = null)
  162. {
  163. $this->_connect();
  164. $sql = null;
  165. // Default transaction level in sql server
  166. if ($level === null)
  167. {
  168. $level = SQLSRV_TXN_READ_COMMITTED;
  169. }
  170. switch ($level) {
  171. case SQLSRV_TXN_READ_UNCOMMITTED:
  172. $sql = "READ UNCOMMITTED";
  173. break;
  174. case SQLSRV_TXN_READ_COMMITTED:
  175. $sql = "READ COMMITTED";
  176. break;
  177. case SQLSRV_TXN_REPEATABLE_READ:
  178. $sql = "REPEATABLE READ";
  179. break;
  180. case SQLSRV_TXN_SNAPSHOT:
  181. $sql = "SNAPSHOT";
  182. break;
  183. case SQLSRV_TXN_SERIALIZABLE:
  184. $sql = "SERIALIZABLE";
  185. break;
  186. default:
  187. require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
  188. throw new Zend_Db_Adapter_Sqlsrv_Exception("Invalid transaction isolation level mode '$level' specified");
  189. }
  190. if (!sqlsrv_query($this->_connection, "SET TRANSACTION ISOLATION LEVEL $sql;")) {
  191. require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
  192. throw new Zend_Db_Adapter_Sqlsrv_Exception("Transaction cannot be changed to '$level'");
  193. }
  194. return true;
  195. }
  196. /**
  197. * Test if a connection is active
  198. *
  199. * @return boolean
  200. */
  201. public function isConnected()
  202. {
  203. return (is_resource($this->_connection)
  204. && (get_resource_type($this->_connection) == 'SQL Server Connection')
  205. );
  206. }
  207. /**
  208. * Force the connection to close.
  209. *
  210. * @return void
  211. */
  212. public function closeConnection()
  213. {
  214. if ($this->isConnected()) {
  215. sqlsrv_close($this->_connection);
  216. }
  217. $this->_connection = null;
  218. }
  219. /**
  220. * Returns an SQL statement for preparation.
  221. *
  222. * @param string $sql The SQL statement with placeholders.
  223. * @return Zend_Db_Statement_Sqlsrv
  224. */
  225. public function prepare($sql)
  226. {
  227. $this->_connect();
  228. $stmtClass = $this->_defaultStmtClass;
  229. if (!class_exists($stmtClass)) {
  230. require_once 'Zend/Loader.php';
  231. Zend_Loader::loadClass($stmtClass);
  232. }
  233. $stmt = new $stmtClass($this, $sql);
  234. $stmt->setFetchMode($this->_fetchMode);
  235. return $stmt;
  236. }
  237. /**
  238. * Quote a raw string.
  239. *
  240. * @param string $value Raw string
  241. * @return string Quoted string
  242. */
  243. protected function _quote($value)
  244. {
  245. if (is_int($value)) {
  246. return $value;
  247. } elseif (is_float($value)) {
  248. return sprintf('%F', $value);
  249. }
  250. return "'" . str_replace("'", "''", $value) . "'";
  251. }
  252. /**
  253. * Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
  254. *
  255. * As a convention, on RDBMS brands that support sequences
  256. * (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence
  257. * from the arguments and returns the last id generated by that sequence.
  258. * On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
  259. * returns the last value generated for such a column, and the table name
  260. * argument is disregarded.
  261. *
  262. * @param string $tableName OPTIONAL Name of table.
  263. * @param string $primaryKey OPTIONAL Name of primary key column.
  264. * @return string
  265. */
  266. public function lastInsertId($tableName = null, $primaryKey = null)
  267. {
  268. if ($tableName) {
  269. $tableName = $this->quote($tableName);
  270. $sql = 'SELECT IDENT_CURRENT (' . $tableName . ') as Current_Identity';
  271. return (string) $this->fetchOne($sql);
  272. }
  273. if ($this->_lastInsertId > 0) {
  274. return (string) $this->_lastInsertId;
  275. }
  276. $sql = $this->_lastInsertSQL;
  277. return (string) $this->fetchOne($sql);
  278. }
  279. /**
  280. * Inserts a table row with specified data.
  281. *
  282. * @param mixed $table The table to insert data into.
  283. * @param array $bind Column-value pairs.
  284. * @return int The number of affected rows.
  285. */
  286. public function insert($table, array $bind)
  287. {
  288. // extract and quote col names from the array keys
  289. $cols = array();
  290. $vals = array();
  291. foreach ($bind as $col => $val) {
  292. $cols[] = $this->quoteIdentifier($col, true);
  293. if ($val instanceof Zend_Db_Expr) {
  294. $vals[] = $val->__toString();
  295. unset($bind[$col]);
  296. } else {
  297. $vals[] = '?';
  298. }
  299. }
  300. // build the statement
  301. $sql = "INSERT INTO "
  302. . $this->quoteIdentifier($table, true)
  303. . ' (' . implode(', ', $cols) . ') '
  304. . 'VALUES (' . implode(', ', $vals) . ')'
  305. . ' ' . $this->_lastInsertSQL;
  306. // execute the statement and return the number of affected rows
  307. $stmt = $this->query($sql, array_values($bind));
  308. $result = $stmt->rowCount();
  309. $stmt->nextRowset();
  310. $this->_lastInsertId = $stmt->fetchColumn();
  311. return $result;
  312. }
  313. /**
  314. * Returns a list of the tables in the database.
  315. *
  316. * @return array
  317. */
  318. public function listTables()
  319. {
  320. $this->_connect();
  321. $sql = "SELECT name FROM sysobjects WHERE type = 'U' ORDER BY name";
  322. return $this->fetchCol($sql);
  323. }
  324. /**
  325. * Returns the column descriptions for a table.
  326. *
  327. * The return value is an associative array keyed by the column name,
  328. * as returned by the RDBMS.
  329. *
  330. * The value of each array element is an associative array
  331. * with the following keys:
  332. *
  333. * SCHEMA_NAME => string; name of schema
  334. * TABLE_NAME => string;
  335. * COLUMN_NAME => string; column name
  336. * COLUMN_POSITION => number; ordinal position of column in table
  337. * DATA_TYPE => string; SQL datatype name of column
  338. * DEFAULT => string; default expression of column, null if none
  339. * NULLABLE => boolean; true if column can have nulls
  340. * LENGTH => number; length of CHAR/VARCHAR
  341. * SCALE => number; scale of NUMERIC/DECIMAL
  342. * PRECISION => number; precision of NUMERIC/DECIMAL
  343. * UNSIGNED => boolean; unsigned property of an integer type
  344. * PRIMARY => boolean; true if column is part of the primary key
  345. * PRIMARY_POSITION => integer; position of column in primary key
  346. * IDENTITY => integer; true if column is auto-generated with unique values
  347. *
  348. * @todo Discover integer unsigned property.
  349. *
  350. * @param string $tableName
  351. * @param string $schemaName OPTIONAL
  352. * @return array
  353. */
  354. public function describeTable($tableName, $schemaName = null)
  355. {
  356. /**
  357. * Discover metadata information about this table.
  358. */
  359. $sql = "exec sp_columns @table_name = " . $this->quoteIdentifier($tableName, true);
  360. $stmt = $this->query($sql);
  361. $result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
  362. $owner = 1;
  363. $table_name = 2;
  364. $column_name = 3;
  365. $type_name = 5;
  366. $precision = 6;
  367. $length = 7;
  368. $scale = 8;
  369. $nullable = 10;
  370. $column_def = 12;
  371. $column_position = 16;
  372. /**
  373. * Discover primary key column(s) for this table.
  374. */
  375. $tableOwner = $result[0][$owner];
  376. $sql = "exec sp_pkeys @table_owner = " . $tableOwner
  377. . ", @table_name = " . $this->quoteIdentifier($tableName, true);
  378. $stmt = $this->query($sql);
  379. $primaryKeysResult = $stmt->fetchAll(Zend_Db::FETCH_NUM);
  380. $primaryKeyColumn = array();
  381. // Per http://msdn.microsoft.com/en-us/library/ms189813.aspx,
  382. // results from sp_keys stored procedure are:
  383. // 0=TABLE_QUALIFIER 1=TABLE_OWNER 2=TABLE_NAME 3=COLUMN_NAME 4=KEY_SEQ 5=PK_NAME
  384. $pkey_column_name = 3;
  385. $pkey_key_seq = 4;
  386. foreach ($primaryKeysResult as $pkeysRow) {
  387. $primaryKeyColumn[$pkeysRow[$pkey_column_name]] = $pkeysRow[$pkey_key_seq];
  388. }
  389. $desc = array();
  390. $p = 1;
  391. foreach ($result as $key => $row) {
  392. $identity = false;
  393. $words = explode(' ', $row[$type_name], 2);
  394. if (isset($words[0])) {
  395. $type = $words[0];
  396. if (isset($words[1])) {
  397. $identity = (bool) preg_match('/identity/', $words[1]);
  398. }
  399. }
  400. $isPrimary = array_key_exists($row[$column_name], $primaryKeyColumn);
  401. if ($isPrimary) {
  402. $primaryPosition = $primaryKeyColumn[$row[$column_name]];
  403. } else {
  404. $primaryPosition = null;
  405. }
  406. $desc[$this->foldCase($row[$column_name])] = array(
  407. 'SCHEMA_NAME' => null, // @todo
  408. 'TABLE_NAME' => $this->foldCase($row[$table_name]),
  409. 'COLUMN_NAME' => $this->foldCase($row[$column_name]),
  410. 'COLUMN_POSITION' => (int) $row[$column_position],
  411. 'DATA_TYPE' => $type,
  412. 'DEFAULT' => $row[$column_def],
  413. 'NULLABLE' => (bool) $row[$nullable],
  414. 'LENGTH' => $row[$length],
  415. 'SCALE' => $row[$scale],
  416. 'PRECISION' => $row[$precision],
  417. 'UNSIGNED' => null, // @todo
  418. 'PRIMARY' => $isPrimary,
  419. 'PRIMARY_POSITION' => $primaryPosition,
  420. 'IDENTITY' => $identity,
  421. );
  422. }
  423. return $desc;
  424. }
  425. /**
  426. * Leave autocommit mode and begin a transaction.
  427. *
  428. * @return void
  429. * @throws Zend_Db_Adapter_Sqlsrv_Exception
  430. */
  431. protected function _beginTransaction()
  432. {
  433. if (!sqlsrv_begin_transaction($this->_connection)) {
  434. require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
  435. throw new Zend_Db_Adapter_Sqlsrv_Exception(sqlsrv_errors());
  436. }
  437. }
  438. /**
  439. * Commit a transaction and return to autocommit mode.
  440. *
  441. * @return void
  442. * @throws Zend_Db_Adapter_Sqlsrv_Exception
  443. */
  444. protected function _commit()
  445. {
  446. if (!sqlsrv_commit($this->_connection)) {
  447. require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
  448. throw new Zend_Db_Adapter_Sqlsrv_Exception(sqlsrv_errors());
  449. }
  450. }
  451. /**
  452. * Roll back a transaction and return to autocommit mode.
  453. *
  454. * @return void
  455. * @throws Zend_Db_Adapter_Sqlsrv_Exception
  456. */
  457. protected function _rollBack()
  458. {
  459. if (!sqlsrv_rollback($this->_connection)) {
  460. require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
  461. throw new Zend_Db_Adapter_Sqlsrv_Exception(sqlsrv_errors());
  462. }
  463. }
  464. /**
  465. * Set the fetch mode.
  466. *
  467. * @todo Support FETCH_CLASS and FETCH_INTO.
  468. *
  469. * @param integer $mode A fetch mode.
  470. * @return void
  471. * @throws Zend_Db_Adapter_Sqlsrv_Exception
  472. */
  473. public function setFetchMode($mode)
  474. {
  475. switch ($mode) {
  476. case Zend_Db::FETCH_NUM: // seq array
  477. case Zend_Db::FETCH_ASSOC: // assoc array
  478. case Zend_Db::FETCH_BOTH: // seq+assoc array
  479. case Zend_Db::FETCH_OBJ: // object
  480. $this->_fetchMode = $mode;
  481. break;
  482. case Zend_Db::FETCH_BOUND: // bound to PHP variable
  483. require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
  484. throw new Zend_Db_Adapter_Sqlsrv_Exception('FETCH_BOUND is not supported yet');
  485. break;
  486. default:
  487. require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
  488. throw new Zend_Db_Adapter_Sqlsrv_Exception("Invalid fetch mode '$mode' specified");
  489. break;
  490. }
  491. }
  492. /**
  493. * Adds an adapter-specific LIMIT clause to the SELECT statement.
  494. *
  495. * @param string $sql
  496. * @param integer $count
  497. * @param integer $offset OPTIONAL
  498. * @return string
  499. * @throws Zend_Db_Adapter_Sqlsrv_Exception
  500. */
  501. public function limit($sql, $count, $offset = 0)
  502. {
  503. $count = intval($count);
  504. if ($count <= 0) {
  505. require_once 'Zend/Db/Adapter/Exception.php';
  506. throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid");
  507. }
  508. $offset = intval($offset);
  509. if ($offset < 0) {
  510. /** @see Zend_Db_Adapter_Exception */
  511. require_once 'Zend/Db/Adapter/Exception.php';
  512. throw new Zend_Db_Adapter_Exception("LIMIT argument offset=$offset is not valid");
  513. }
  514. $orderby = stristr($sql, 'ORDER BY');
  515. if ($orderby !== false) {
  516. $sort = (stripos($orderby, ' desc') !== false) ? 'desc' : 'asc';
  517. $order = str_ireplace('ORDER BY', '', $orderby);
  518. $order = trim(preg_replace('/\bASC\b|\bDESC\b/i', '', $order));
  519. }
  520. $sql = preg_replace('/^SELECT\s/i', 'SELECT TOP ' . ($count+$offset) . ' ', $sql);
  521. $sql = 'SELECT * FROM (SELECT TOP ' . $count . ' * FROM (' . $sql . ') AS inner_tbl';
  522. if ($orderby !== false) {
  523. $sql .= ' ORDER BY ' . $order . ' ';
  524. $sql .= (stripos($sort, 'asc') !== false) ? 'DESC' : 'ASC';
  525. }
  526. $sql .= ') AS outer_tbl';
  527. if ($orderby !== false) {
  528. $sql .= ' ORDER BY ' . $order . ' ' . $sort;
  529. }
  530. return $sql;
  531. }
  532. /**
  533. * Check if the adapter supports real SQL parameters.
  534. *
  535. * @param string $type 'positional' or 'named'
  536. * @return bool
  537. */
  538. public function supportsParameters($type)
  539. {
  540. if ($type == 'positional') {
  541. return true;
  542. }
  543. // if its 'named' or anything else
  544. return false;
  545. }
  546. /**
  547. * Retrieve server version in PHP style
  548. *
  549. * @return string
  550. */
  551. public function getServerVersion()
  552. {
  553. $this->_connect();
  554. $version = sqlsrv_client_info($this->_connection);
  555. if ($version !== false) {
  556. return $version['DriverVer'];
  557. }
  558. return null;
  559. }
  560. }