SQLSrvStatement.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the MIT license. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\DBAL\Driver\SQLSrv;
  20. use PDO;
  21. use IteratorAggregate;
  22. use Doctrine\DBAL\Driver\Statement;
  23. /**
  24. * SQL Server Statement.
  25. *
  26. * @since 2.3
  27. * @author Benjamin Eberlei <kontakt@beberlei.de>
  28. */
  29. class SQLSrvStatement implements IteratorAggregate, Statement
  30. {
  31. /**
  32. * The SQLSRV Resource.
  33. *
  34. * @var resource
  35. */
  36. private $conn;
  37. /**
  38. * The SQL statement to execute.
  39. *
  40. * @var string
  41. */
  42. private $sql;
  43. /**
  44. * The SQLSRV statement resource.
  45. *
  46. * @var resource
  47. */
  48. private $stmt;
  49. /**
  50. * References to the variables bound as statement parameters.
  51. *
  52. * @var array
  53. */
  54. private $variables = array();
  55. /**
  56. * Bound parameter types.
  57. *
  58. * @var array
  59. */
  60. private $types = array();
  61. /**
  62. * Translations.
  63. *
  64. * @var array
  65. */
  66. private static $fetchMap = array(
  67. PDO::FETCH_BOTH => SQLSRV_FETCH_BOTH,
  68. PDO::FETCH_ASSOC => SQLSRV_FETCH_ASSOC,
  69. PDO::FETCH_NUM => SQLSRV_FETCH_NUMERIC,
  70. );
  71. /**
  72. * The name of the default class to instantiate when fetch mode is \PDO::FETCH_CLASS.
  73. *
  74. * @var string
  75. */
  76. private $defaultFetchClass = '\stdClass';
  77. /**
  78. * The constructor arguments for the default class to instantiate when fetch mode is \PDO::FETCH_CLASS.
  79. *
  80. * @var string
  81. */
  82. private $defaultFetchClassCtorArgs = array();
  83. /**
  84. * The fetch style.
  85. *
  86. * @param integer
  87. */
  88. private $defaultFetchMode = PDO::FETCH_BOTH;
  89. /**
  90. * The last insert ID.
  91. *
  92. * @var \Doctrine\DBAL\Driver\SQLSrv\LastInsertId|null
  93. */
  94. private $lastInsertId;
  95. /**
  96. * Indicates whether the statement is in the state when fetching results is possible
  97. *
  98. * @var bool
  99. */
  100. private $result = false;
  101. /**
  102. * Append to any INSERT query to retrieve the last insert id.
  103. *
  104. * @var string
  105. */
  106. const LAST_INSERT_ID_SQL = ';SELECT SCOPE_IDENTITY() AS LastInsertId;';
  107. /**
  108. * @param resource $conn
  109. * @param string $sql
  110. * @param \Doctrine\DBAL\Driver\SQLSrv\LastInsertId|null $lastInsertId
  111. */
  112. public function __construct($conn, $sql, LastInsertId $lastInsertId = null)
  113. {
  114. $this->conn = $conn;
  115. $this->sql = $sql;
  116. if (stripos($sql, 'INSERT INTO ') === 0) {
  117. $this->sql .= self::LAST_INSERT_ID_SQL;
  118. $this->lastInsertId = $lastInsertId;
  119. }
  120. }
  121. /**
  122. * {@inheritdoc}
  123. */
  124. public function bindValue($param, $value, $type = null)
  125. {
  126. if (!is_numeric($param)) {
  127. throw new SQLSrvException(
  128. 'sqlsrv does not support named parameters to queries, use question mark (?) placeholders instead.'
  129. );
  130. }
  131. $this->variables[$param] = $value;
  132. $this->types[$param] = $type;
  133. }
  134. /**
  135. * {@inheritdoc}
  136. */
  137. public function bindParam($column, &$variable, $type = null, $length = null)
  138. {
  139. if (!is_numeric($column)) {
  140. throw new SQLSrvException("sqlsrv does not support named parameters to queries, use question mark (?) placeholders instead.");
  141. }
  142. $this->variables[$column] =& $variable;
  143. $this->types[$column] = $type;
  144. // unset the statement resource if it exists as the new one will need to be bound to the new variable
  145. $this->stmt = null;
  146. }
  147. /**
  148. * {@inheritdoc}
  149. */
  150. public function closeCursor()
  151. {
  152. // not having the result means there's nothing to close
  153. if (!$this->result) {
  154. return true;
  155. }
  156. // emulate it by fetching and discarding rows, similarly to what PDO does in this case
  157. // @link http://php.net/manual/en/pdostatement.closecursor.php
  158. // @link https://github.com/php/php-src/blob/php-7.0.11/ext/pdo/pdo_stmt.c#L2075
  159. // deliberately do not consider multiple result sets, since doctrine/dbal doesn't support them
  160. while (sqlsrv_fetch($this->stmt));
  161. $this->result = false;
  162. return true;
  163. }
  164. /**
  165. * {@inheritdoc}
  166. */
  167. public function columnCount()
  168. {
  169. return sqlsrv_num_fields($this->stmt);
  170. }
  171. /**
  172. * {@inheritdoc}
  173. */
  174. public function errorCode()
  175. {
  176. $errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
  177. if ($errors) {
  178. return $errors[0]['code'];
  179. }
  180. return false;
  181. }
  182. /**
  183. * {@inheritdoc}
  184. */
  185. public function errorInfo()
  186. {
  187. return sqlsrv_errors(SQLSRV_ERR_ERRORS);
  188. }
  189. /**
  190. * {@inheritdoc}
  191. */
  192. public function execute($params = null)
  193. {
  194. if ($params) {
  195. $hasZeroIndex = array_key_exists(0, $params);
  196. foreach ($params as $key => $val) {
  197. $key = ($hasZeroIndex && is_numeric($key)) ? $key + 1 : $key;
  198. $this->bindValue($key, $val);
  199. }
  200. }
  201. if ( ! $this->stmt) {
  202. $this->stmt = $this->prepare();
  203. }
  204. if (!sqlsrv_execute($this->stmt)) {
  205. throw SQLSrvException::fromSqlSrvErrors();
  206. }
  207. if ($this->lastInsertId) {
  208. sqlsrv_next_result($this->stmt);
  209. sqlsrv_fetch($this->stmt);
  210. $this->lastInsertId->setId(sqlsrv_get_field($this->stmt, 0));
  211. }
  212. $this->result = true;
  213. }
  214. /**
  215. * Prepares SQL Server statement resource
  216. *
  217. * @return resource
  218. * @throws SQLSrvException
  219. */
  220. private function prepare()
  221. {
  222. $params = array();
  223. foreach ($this->variables as $column => &$variable) {
  224. if ($this->types[$column] === \PDO::PARAM_LOB) {
  225. $params[$column - 1] = array(
  226. &$variable,
  227. SQLSRV_PARAM_IN,
  228. SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY),
  229. SQLSRV_SQLTYPE_VARBINARY('max'),
  230. );
  231. } else {
  232. $params[$column - 1] =& $variable;
  233. }
  234. }
  235. $stmt = sqlsrv_prepare($this->conn, $this->sql, $params);
  236. if (!$stmt) {
  237. throw SQLSrvException::fromSqlSrvErrors();
  238. }
  239. return $stmt;
  240. }
  241. /**
  242. * {@inheritdoc}
  243. */
  244. public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null)
  245. {
  246. $this->defaultFetchMode = $fetchMode;
  247. $this->defaultFetchClass = $arg2 ?: $this->defaultFetchClass;
  248. $this->defaultFetchClassCtorArgs = $arg3 ? (array) $arg3 : $this->defaultFetchClassCtorArgs;
  249. return true;
  250. }
  251. /**
  252. * {@inheritdoc}
  253. */
  254. public function getIterator()
  255. {
  256. $data = $this->fetchAll();
  257. return new \ArrayIterator($data);
  258. }
  259. /**
  260. * {@inheritdoc}
  261. */
  262. public function fetch($fetchMode = null)
  263. {
  264. // do not try fetching from the statement if it's not expected to contain result
  265. // in order to prevent exceptional situation
  266. if (!$this->result) {
  267. return false;
  268. }
  269. $args = func_get_args();
  270. $fetchMode = $fetchMode ?: $this->defaultFetchMode;
  271. if (isset(self::$fetchMap[$fetchMode])) {
  272. return sqlsrv_fetch_array($this->stmt, self::$fetchMap[$fetchMode]) ?: false;
  273. }
  274. if ($fetchMode == PDO::FETCH_OBJ || $fetchMode == PDO::FETCH_CLASS) {
  275. $className = $this->defaultFetchClass;
  276. $ctorArgs = $this->defaultFetchClassCtorArgs;
  277. if (count($args) >= 2) {
  278. $className = $args[1];
  279. $ctorArgs = (isset($args[2])) ? $args[2] : array();
  280. }
  281. return sqlsrv_fetch_object($this->stmt, $className, $ctorArgs) ?: false;
  282. }
  283. throw new SQLSrvException("Fetch mode is not supported!");
  284. }
  285. /**
  286. * {@inheritdoc}
  287. */
  288. public function fetchAll($fetchMode = null)
  289. {
  290. $rows = array();
  291. switch ($fetchMode) {
  292. case PDO::FETCH_CLASS:
  293. while ($row = call_user_func_array(array($this, 'fetch'), func_get_args())) {
  294. $rows[] = $row;
  295. }
  296. break;
  297. case PDO::FETCH_COLUMN:
  298. while ($row = $this->fetchColumn()) {
  299. $rows[] = $row;
  300. }
  301. break;
  302. default:
  303. while ($row = $this->fetch($fetchMode)) {
  304. $rows[] = $row;
  305. }
  306. }
  307. return $rows;
  308. }
  309. /**
  310. * {@inheritdoc}
  311. */
  312. public function fetchColumn($columnIndex = 0)
  313. {
  314. $row = $this->fetch(PDO::FETCH_NUM);
  315. if (false === $row) {
  316. return false;
  317. }
  318. return isset($row[$columnIndex]) ? $row[$columnIndex] : null;
  319. }
  320. /**
  321. * {@inheritdoc}
  322. */
  323. public function rowCount()
  324. {
  325. return sqlsrv_rows_affected($this->stmt);
  326. }
  327. }