Sqlsrv.php 20 KB

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