PageRenderTime 50ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/concrete/libraries/3rdparty/Zend/Db/Adapter/Sqlsrv.php

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