PageRenderTime 51ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Joomla/Database/Sqlsrv/SqlsrvDriver.php

https://github.com/dianaprajescu/joomla-framework
PHP | 1081 lines | 699 code | 100 blank | 282 comment | 40 complexity | a341a0d5bd0f90ad966aaf2fb2c74ded MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. /**
  3. * Part of the Joomla Framework Database Package
  4. *
  5. * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
  6. * @license GNU General Public License version 2 or later; see LICENSE
  7. */
  8. namespace Joomla\Database\Sqlsrv;
  9. use Psr\Log;
  10. use Joomla\Database\DatabaseDriver;
  11. /**
  12. * SQL Server database driver
  13. *
  14. * @see http://msdn.microsoft.com/en-us/library/cc296152(SQL.90).aspx
  15. * @since 1.0
  16. */
  17. class SqlsrvDriver extends DatabaseDriver
  18. {
  19. /**
  20. * The name of the database driver.
  21. *
  22. * @var string
  23. * @since 1.0
  24. */
  25. public $name = 'sqlsrv';
  26. /**
  27. * The character(s) used to quote SQL statement names such as table names or field names,
  28. * etc. The child classes should define this as necessary. If a single character string the
  29. * same character is used for both sides of the quoted name, else the first character will be
  30. * used for the opening quote and the second for the closing quote.
  31. *
  32. * @var string
  33. * @since 1.0
  34. */
  35. protected $nameQuote;
  36. /**
  37. * The null or zero representation of a timestamp for the database driver. This should be
  38. * defined in child classes to hold the appropriate value for the engine.
  39. *
  40. * @var string
  41. * @since 1.0
  42. */
  43. protected $nullDate = '1900-01-01 00:00:00';
  44. /**
  45. * @var string The minimum supported database version.
  46. * @since 1.0
  47. */
  48. protected static $dbMinimum = '10.50.1600.1';
  49. /**
  50. * Test to see if the SQLSRV connector is available.
  51. *
  52. * @return boolean True on success, false otherwise.
  53. *
  54. * @since 1.0
  55. */
  56. public static function isSupported()
  57. {
  58. return (function_exists('sqlsrv_connect'));
  59. }
  60. /**
  61. * Constructor.
  62. *
  63. * @param array $options List of options used to configure the connection
  64. *
  65. * @since 1.0
  66. */
  67. public function __construct($options)
  68. {
  69. // Get some basic values from the options.
  70. $options['host'] = (isset($options['host'])) ? $options['host'] : 'localhost';
  71. $options['user'] = (isset($options['user'])) ? $options['user'] : '';
  72. $options['password'] = (isset($options['password'])) ? $options['password'] : '';
  73. $options['database'] = (isset($options['database'])) ? $options['database'] : '';
  74. $options['select'] = (isset($options['select'])) ? (bool) $options['select'] : true;
  75. // Finalize initialisation
  76. parent::__construct($options);
  77. }
  78. /**
  79. * Destructor.
  80. *
  81. * @since 1.0
  82. */
  83. public function __destruct()
  84. {
  85. if (is_resource($this->connection))
  86. {
  87. sqlsrv_close($this->connection);
  88. }
  89. }
  90. /**
  91. * Connects to the database if needed.
  92. *
  93. * @return void Returns void if the database connected successfully.
  94. *
  95. * @since 1.0
  96. * @throws \RuntimeException
  97. */
  98. public function connect()
  99. {
  100. if ($this->connection)
  101. {
  102. return;
  103. }
  104. // Build the connection configuration array.
  105. $config = array(
  106. 'Database' => $this->options['database'],
  107. 'uid' => $this->options['user'],
  108. 'pwd' => $this->options['password'],
  109. 'CharacterSet' => 'UTF-8',
  110. 'ReturnDatesAsStrings' => true);
  111. // Make sure the SQLSRV extension for PHP is installed and enabled.
  112. if (!function_exists('sqlsrv_connect'))
  113. {
  114. throw new \RuntimeException('PHP extension sqlsrv_connect is not available.');
  115. }
  116. // Attempt to connect to the server.
  117. if (!($this->connection = @ sqlsrv_connect($this->options['host'], $config)))
  118. {
  119. throw new \RuntimeException('Database sqlsrv_connect failed');
  120. }
  121. // Make sure that DB warnings are not returned as errors.
  122. sqlsrv_configure('WarningsReturnAsErrors', 0);
  123. // If auto-select is enabled select the given database.
  124. if ($this->options['select'] && !empty($this->options['database']))
  125. {
  126. $this->select($this->options['database']);
  127. }
  128. }
  129. /**
  130. * Disconnects the database.
  131. *
  132. * @return void
  133. *
  134. * @since 1.0
  135. */
  136. public function disconnect()
  137. {
  138. // Close the connection.
  139. if (is_resource($this->connection))
  140. {
  141. sqlsrv_close($this->connection);
  142. }
  143. $this->connection = null;
  144. }
  145. /**
  146. * Get table constraints
  147. *
  148. * @param string $tableName The name of the database table.
  149. *
  150. * @return array Any constraints available for the table.
  151. *
  152. * @since 1.0
  153. */
  154. protected function getTableConstraints($tableName)
  155. {
  156. $this->connect();
  157. $query = $this->getQuery(true);
  158. $this->setQuery(
  159. 'SELECT CONSTRAINT_NAME FROM' . ' INFORMATION_SCHEMA.TABLE_CONSTRAINTS' . ' WHERE TABLE_NAME = ' . $query->quote($tableName)
  160. );
  161. return $this->loadColumn();
  162. }
  163. /**
  164. * Rename constraints.
  165. *
  166. * @param array $constraints Array(strings) of table constraints
  167. * @param string $prefix A string
  168. * @param string $backup A string
  169. *
  170. * @return void
  171. *
  172. * @since 1.0
  173. */
  174. protected function renameConstraints($constraints = array(), $prefix = null, $backup = null)
  175. {
  176. $this->connect();
  177. foreach ($constraints as $constraint)
  178. {
  179. $this->setQuery('sp_rename ' . $constraint . ',' . str_replace($prefix, $backup, $constraint));
  180. $this->execute();
  181. }
  182. }
  183. /**
  184. * Method to escape a string for usage in an SQL statement.
  185. *
  186. * The escaping for MSSQL isn't handled in the driver though that would be nice. Because of this we need
  187. * to handle the escaping ourselves.
  188. *
  189. * @param string $text The string to be escaped.
  190. * @param boolean $extra Optional parameter to provide extra escaping.
  191. *
  192. * @return string The escaped string.
  193. *
  194. * @since 1.0
  195. */
  196. public function escape($text, $extra = false)
  197. {
  198. $result = addslashes($text);
  199. $result = str_replace("\'", "''", $result);
  200. $result = str_replace('\"', '"', $result);
  201. $result = str_replace('\/', '/', $result);
  202. if ($extra)
  203. {
  204. // We need the below str_replace since the search in sql server doesn't recognize _ character.
  205. $result = str_replace('_', '[_]', $result);
  206. }
  207. return $result;
  208. }
  209. /**
  210. * Determines if the connection to the server is active.
  211. *
  212. * @return boolean True if connected to the database engine.
  213. *
  214. * @since 1.0
  215. */
  216. public function connected()
  217. {
  218. // TODO: Run a blank query here
  219. return true;
  220. }
  221. /**
  222. * Drops a table from the database.
  223. *
  224. * @param string $tableName The name of the database table to drop.
  225. * @param boolean $ifExists Optionally specify that the table must exist before it is dropped.
  226. *
  227. * @return SqlsrvDriver Returns this object to support chaining.
  228. *
  229. * @since 1.0
  230. */
  231. public function dropTable($tableName, $ifExists = true)
  232. {
  233. $this->connect();
  234. $query = $this->getQuery(true);
  235. if ($ifExists)
  236. {
  237. $this->setQuery(
  238. 'IF EXISTS(SELECT TABLE_NAME FROM' . ' INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ' . $query->quote($tableName) . ') DROP TABLE ' . $tableName
  239. );
  240. }
  241. else
  242. {
  243. $this->setQuery('DROP TABLE ' . $tableName);
  244. }
  245. $this->execute();
  246. return $this;
  247. }
  248. /**
  249. * Get the number of affected rows for the previous executed SQL statement.
  250. *
  251. * @return integer The number of affected rows.
  252. *
  253. * @since 1.0
  254. */
  255. public function getAffectedRows()
  256. {
  257. $this->connect();
  258. return sqlsrv_rows_affected($this->cursor);
  259. }
  260. /**
  261. * Method to get the database collation in use by sampling a text field of a table in the database.
  262. *
  263. * @return mixed The collation in use by the database or boolean false if not supported.
  264. *
  265. * @since 1.0
  266. */
  267. public function getCollation()
  268. {
  269. // TODO: Not fake this
  270. return 'MSSQL UTF-8 (UCS2)';
  271. }
  272. /**
  273. * Get the number of returned rows for the previous executed SQL statement.
  274. *
  275. * @param resource $cursor An optional database cursor resource to extract the row count from.
  276. *
  277. * @return integer The number of returned rows.
  278. *
  279. * @since 1.0
  280. */
  281. public function getNumRows($cursor = null)
  282. {
  283. $this->connect();
  284. return sqlsrv_num_rows($cursor ? $cursor : $this->cursor);
  285. }
  286. /**
  287. * Retrieves field information about the given tables.
  288. *
  289. * @param mixed $table A table name
  290. * @param boolean $typeOnly True to only return field types.
  291. *
  292. * @return array An array of fields.
  293. *
  294. * @since 1.0
  295. * @throws \RuntimeException
  296. */
  297. public function getTableColumns($table, $typeOnly = true)
  298. {
  299. $result = array();
  300. $table_temp = $this->replacePrefix((string) $table);
  301. // Set the query to get the table fields statement.
  302. $this->setQuery(
  303. 'SELECT column_name as Field, data_type as Type, is_nullable as \'Null\', column_default as \'Default\'' .
  304. ' FROM information_schema.columns' . ' WHERE table_name = ' . $this->quote($table_temp)
  305. );
  306. $fields = $this->loadObjectList();
  307. // If we only want the type as the value add just that to the list.
  308. if ($typeOnly)
  309. {
  310. foreach ($fields as $field)
  311. {
  312. $result[$field->Field] = preg_replace("/[(0-9)]/", '', $field->Type);
  313. }
  314. }
  315. else
  316. // If we want the whole field data object add that to the list.
  317. {
  318. foreach ($fields as $field)
  319. {
  320. $result[$field->Field] = $field;
  321. }
  322. }
  323. return $result;
  324. }
  325. /**
  326. * Shows the table CREATE statement that creates the given tables.
  327. *
  328. * This is unsupported by MSSQL.
  329. *
  330. * @param mixed $tables A table name or a list of table names.
  331. *
  332. * @return array A list of the create SQL for the tables.
  333. *
  334. * @since 1.0
  335. * @throws \RuntimeException
  336. */
  337. public function getTableCreate($tables)
  338. {
  339. $this->connect();
  340. return '';
  341. }
  342. /**
  343. * Get the details list of keys for a table.
  344. *
  345. * @param string $table The name of the table.
  346. *
  347. * @return array An array of the column specification for the table.
  348. *
  349. * @since 1.0
  350. * @throws \RuntimeException
  351. */
  352. public function getTableKeys($table)
  353. {
  354. $this->connect();
  355. // TODO To implement.
  356. return array();
  357. }
  358. /**
  359. * Method to get an array of all tables in the database.
  360. *
  361. * @return array An array of all the tables in the database.
  362. *
  363. * @since 1.0
  364. * @throws \RuntimeException
  365. */
  366. public function getTableList()
  367. {
  368. $this->connect();
  369. // Set the query to get the tables statement.
  370. $this->setQuery('SELECT name FROM ' . $this->getDatabase() . '.sys.Tables WHERE type = \'U\';');
  371. $tables = $this->loadColumn();
  372. return $tables;
  373. }
  374. /**
  375. * Get the version of the database connector.
  376. *
  377. * @return string The database connector version.
  378. *
  379. * @since 1.0
  380. */
  381. public function getVersion()
  382. {
  383. $this->connect();
  384. $version = sqlsrv_server_info($this->connection);
  385. return $version['SQLServerVersion'];
  386. }
  387. /**
  388. * Inserts a row into a table based on an object's properties.
  389. *
  390. * @param string $table The name of the database table to insert into.
  391. * @param object &$object A reference to an object whose public properties match the table fields.
  392. * @param string $key The name of the primary key. If provided the object property is updated.
  393. *
  394. * @return boolean True on success.
  395. *
  396. * @since 1.0
  397. * @throws \RuntimeException
  398. */
  399. public function insertObject($table, &$object, $key = null)
  400. {
  401. $fields = array();
  402. $values = array();
  403. $statement = 'INSERT INTO ' . $this->quoteName($table) . ' (%s) VALUES (%s)';
  404. foreach (get_object_vars($object) as $k => $v)
  405. {
  406. // Only process non-null scalars.
  407. if (is_array($v) or is_object($v) or $v === null)
  408. {
  409. continue;
  410. }
  411. if (!$this->checkFieldExists($table, $k))
  412. {
  413. continue;
  414. }
  415. if ($k[0] == '_')
  416. {
  417. // Internal field
  418. continue;
  419. }
  420. if ($k == $key && $key == 0)
  421. {
  422. continue;
  423. }
  424. $fields[] = $this->quoteName($k);
  425. $values[] = $this->Quote($v);
  426. }
  427. // Set the query and execute the insert.
  428. $this->setQuery(sprintf($statement, implode(',', $fields), implode(',', $values)));
  429. if (!$this->execute())
  430. {
  431. return false;
  432. }
  433. $id = $this->insertid();
  434. if ($key && $id)
  435. {
  436. $object->$key = $id;
  437. }
  438. return true;
  439. }
  440. /**
  441. * Method to get the auto-incremented value from the last INSERT statement.
  442. *
  443. * @return integer The value of the auto-increment field from the last inserted row.
  444. *
  445. * @since 1.0
  446. */
  447. public function insertid()
  448. {
  449. $this->connect();
  450. // TODO: SELECT IDENTITY
  451. $this->setQuery('SELECT @@IDENTITY');
  452. return (int) $this->loadResult();
  453. }
  454. /**
  455. * Method to get the first field of the first row of the result set from the database query.
  456. *
  457. * @return mixed The return value or null if the query failed.
  458. *
  459. * @since 1.0
  460. * @throws \RuntimeException
  461. */
  462. public function loadResult()
  463. {
  464. $ret = null;
  465. // Execute the query and get the result set cursor.
  466. if (!($cursor = $this->execute()))
  467. {
  468. return null;
  469. }
  470. // Get the first row from the result set as an array.
  471. if ($row = sqlsrv_fetch_array($cursor, SQLSRV_FETCH_NUMERIC))
  472. {
  473. $ret = $row[0];
  474. }
  475. // Free up system resources and return.
  476. $this->freeResult($cursor);
  477. // For SQLServer - we need to strip slashes
  478. $ret = stripslashes($ret);
  479. return $ret;
  480. }
  481. /**
  482. * Execute the SQL statement.
  483. *
  484. * @return mixed A database cursor resource on success, boolean false on failure.
  485. *
  486. * @since 1.0
  487. * @throws \Exception
  488. * @throws \RuntimeException
  489. */
  490. public function execute()
  491. {
  492. $this->connect();
  493. if (!is_resource($this->connection))
  494. {
  495. $this->log(
  496. Log\LogLevel::ERROR,
  497. 'Database query failed (error #{code}): {message}',
  498. array('code' => $this->errorNum, 'message' => $this->errorMsg)
  499. );
  500. throw new \RuntimeException($this->errorMsg, $this->errorNum);
  501. }
  502. // Take a local copy so that we don't modify the original query and cause issues later
  503. $sql = $this->replacePrefix((string) $this->sql);
  504. if ($this->limit > 0 || $this->offset > 0)
  505. {
  506. $sql = $this->limit($sql, $this->limit, $this->offset);
  507. }
  508. // Increment the query counter.
  509. $this->count++;
  510. // If debugging is enabled then let's log the query.
  511. if ($this->debug)
  512. {
  513. // Add the query to the object queue.
  514. $this->log(
  515. Log\LogLevel::DEBUG,
  516. '{sql}',
  517. array('sql' => $sql, 'category' => 'databasequery')
  518. );
  519. }
  520. // Reset the error values.
  521. $this->errorNum = 0;
  522. $this->errorMsg = '';
  523. // SQLSrv_num_rows requires a static or keyset cursor.
  524. if (strncmp(ltrim(strtoupper($sql)), 'SELECT', strlen('SELECT')) == 0)
  525. {
  526. $array = array('Scrollable' => SQLSRV_CURSOR_KEYSET);
  527. }
  528. else
  529. {
  530. $array = array();
  531. }
  532. // Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost.
  533. $this->cursor = @sqlsrv_query($this->connection, $sql, array(), $array);
  534. // If an error occurred handle it.
  535. if (!$this->cursor)
  536. {
  537. // Check if the server was disconnected.
  538. if (!$this->connected())
  539. {
  540. try
  541. {
  542. // Attempt to reconnect.
  543. $this->connection = null;
  544. $this->connect();
  545. }
  546. catch (\RuntimeException $e)
  547. // If connect fails, ignore that exception and throw the normal exception.
  548. {
  549. // Get the error number and message.
  550. $errors = sqlsrv_errors();
  551. $this->errorNum = $errors[0]['SQLSTATE'];
  552. $this->errorMsg = $errors[0]['message'] . 'SQL=' . $sql;
  553. // Throw the normal query exception.
  554. $this->log(
  555. Log\LogLevel::ERROR,
  556. 'Database query failed (error #{code}): {message}',
  557. array('code' => $this->errorNum, 'message' => $this->errorMsg)
  558. );
  559. throw new \RuntimeException($this->errorMsg, $this->errorNum);
  560. }
  561. // Since we were able to reconnect, run the query again.
  562. return $this->execute();
  563. }
  564. else
  565. // The server was not disconnected.
  566. {
  567. // Get the error number and message.
  568. $errors = sqlsrv_errors();
  569. $this->errorNum = $errors[0]['SQLSTATE'];
  570. $this->errorMsg = $errors[0]['message'] . 'SQL=' . $sql;
  571. // Throw the normal query exception.
  572. $this->log(
  573. Log\LogLevel::ERROR,
  574. 'Database query failed (error #{code}): {message}',
  575. array('code' => $this->errorNum, 'message' => $this->errorMsg)
  576. );
  577. throw new \RuntimeException($this->errorMsg, $this->errorNum);
  578. }
  579. }
  580. return $this->cursor;
  581. }
  582. /**
  583. * This function replaces a string identifier <var>$prefix</var> with the string held is the
  584. * <var>tablePrefix</var> class variable.
  585. *
  586. * @param string $sql The SQL statement to prepare.
  587. * @param string $prefix The common table prefix.
  588. *
  589. * @return string The processed SQL statement.
  590. *
  591. * @since 1.0
  592. */
  593. public function replacePrefix($sql, $prefix = '#__')
  594. {
  595. $escaped = false;
  596. $startPos = 0;
  597. $quoteChar = '';
  598. $literal = '';
  599. $sql = trim($sql);
  600. $n = strlen($sql);
  601. while ($startPos < $n)
  602. {
  603. $ip = strpos($sql, $prefix, $startPos);
  604. if ($ip === false)
  605. {
  606. break;
  607. }
  608. $j = strpos($sql, "N'", $startPos);
  609. $k = strpos($sql, '"', $startPos);
  610. if (($k !== false) && (($k < $j) || ($j === false)))
  611. {
  612. $quoteChar = '"';
  613. $j = $k;
  614. }
  615. else
  616. {
  617. $quoteChar = "'";
  618. }
  619. if ($j === false)
  620. {
  621. $j = $n;
  622. }
  623. $literal .= str_replace($prefix, $this->tablePrefix, substr($sql, $startPos, $j - $startPos));
  624. $startPos = $j;
  625. $j = $startPos + 1;
  626. if ($j >= $n)
  627. {
  628. break;
  629. }
  630. // Quote comes first, find end of quote
  631. while (true)
  632. {
  633. $k = strpos($sql, $quoteChar, $j);
  634. $escaped = false;
  635. if ($k === false)
  636. {
  637. break;
  638. }
  639. $l = $k - 1;
  640. while ($l >= 0 && $sql{$l} == '\\')
  641. {
  642. $l--;
  643. $escaped = !$escaped;
  644. }
  645. if ($escaped)
  646. {
  647. $j = $k + 1;
  648. continue;
  649. }
  650. break;
  651. }
  652. if ($k === false)
  653. {
  654. // Error in the query - no end quote; ignore it
  655. break;
  656. }
  657. $literal .= substr($sql, $startPos, $k - $startPos + 1);
  658. $startPos = $k + 1;
  659. }
  660. if ($startPos < $n)
  661. {
  662. $literal .= substr($sql, $startPos, $n - $startPos);
  663. }
  664. return $literal;
  665. }
  666. /**
  667. * Select a database for use.
  668. *
  669. * @param string $database The name of the database to select for use.
  670. *
  671. * @return boolean True if the database was successfully selected.
  672. *
  673. * @since 1.0
  674. * @throws \RuntimeException
  675. */
  676. public function select($database)
  677. {
  678. $this->connect();
  679. if (!$database)
  680. {
  681. return false;
  682. }
  683. if (!sqlsrv_query($this->connection, 'USE ' . $database, null, array('scrollable' => SQLSRV_CURSOR_STATIC)))
  684. {
  685. throw new \RuntimeException('Could not connect to database');
  686. }
  687. return true;
  688. }
  689. /**
  690. * Set the connection to use UTF-8 character encoding.
  691. *
  692. * @return boolean True on success.
  693. *
  694. * @since 1.0
  695. */
  696. public function setUTF()
  697. {
  698. // TODO: Remove this?
  699. }
  700. /**
  701. * Method to commit a transaction.
  702. *
  703. * @param boolean $toSavepoint If true, commit to the last savepoint.
  704. *
  705. * @return void
  706. *
  707. * @since 1.0
  708. * @throws \RuntimeException
  709. */
  710. public function transactionCommit($toSavepoint = false)
  711. {
  712. $this->connect();
  713. if (!$toSavepoint || $this->transactionDepth <= 1)
  714. {
  715. if ($this->setQuery('COMMIT TRANSACTION')->execute())
  716. {
  717. $this->transactionDepth = 0;
  718. }
  719. return;
  720. }
  721. $this->transactionDepth--;
  722. }
  723. /**
  724. * Method to roll back a transaction.
  725. *
  726. * @param boolean $toSavepoint If true, rollback to the last savepoint.
  727. *
  728. * @return void
  729. *
  730. * @since 1.0
  731. * @throws \RuntimeException
  732. */
  733. public function transactionRollback($toSavepoint = false)
  734. {
  735. $this->connect();
  736. if (!$toSavepoint || $this->transactionDepth <= 1)
  737. {
  738. if ($this->setQuery('ROLLBACK TRANSACTION')->execute())
  739. {
  740. $this->transactionDepth = 0;
  741. }
  742. return;
  743. }
  744. $savepoint = 'SP_' . ($this->transactionDepth - 1);
  745. $this->setQuery('ROLLBACK TRANSACTION ' . $this->quoteName($savepoint));
  746. if ($this->execute())
  747. {
  748. $this->transactionDepth--;
  749. }
  750. }
  751. /**
  752. * Method to initialize a transaction.
  753. *
  754. * @param boolean $asSavepoint If true and a transaction is already active, a savepoint will be created.
  755. *
  756. * @return void
  757. *
  758. * @since 1.0
  759. * @throws \RuntimeException
  760. */
  761. public function transactionStart($asSavepoint = false)
  762. {
  763. $this->connect();
  764. if (!$asSavepoint || !$this->transactionDepth)
  765. {
  766. if ($this->setQuery('BEGIN TRANSACTION')->execute())
  767. {
  768. $this->transactionDepth = 1;
  769. }
  770. return;
  771. }
  772. $savepoint = 'SP_' . $this->transactionDepth;
  773. $this->setQuery('BEGIN TRANSACTION ' . $this->quoteName($savepoint));
  774. if ($this->execute())
  775. {
  776. $this->transactionDepth++;
  777. }
  778. }
  779. /**
  780. * Method to fetch a row from the result set cursor as an array.
  781. *
  782. * @param mixed $cursor The optional result set cursor from which to fetch the row.
  783. *
  784. * @return mixed Either the next row from the result set or false if there are no more rows.
  785. *
  786. * @since 1.0
  787. */
  788. protected function fetchArray($cursor = null)
  789. {
  790. return sqlsrv_fetch_array($cursor ? $cursor : $this->cursor, SQLSRV_FETCH_NUMERIC);
  791. }
  792. /**
  793. * Method to fetch a row from the result set cursor as an associative array.
  794. *
  795. * @param mixed $cursor The optional result set cursor from which to fetch the row.
  796. *
  797. * @return mixed Either the next row from the result set or false if there are no more rows.
  798. *
  799. * @since 1.0
  800. */
  801. protected function fetchAssoc($cursor = null)
  802. {
  803. return sqlsrv_fetch_array($cursor ? $cursor : $this->cursor, SQLSRV_FETCH_ASSOC);
  804. }
  805. /**
  806. * Method to fetch a row from the result set cursor as an object.
  807. *
  808. * @param mixed $cursor The optional result set cursor from which to fetch the row.
  809. * @param string $class The class name to use for the returned row object.
  810. *
  811. * @return mixed Either the next row from the result set or false if there are no more rows.
  812. *
  813. * @since 1.0
  814. */
  815. protected function fetchObject($cursor = null, $class = 'stdClass')
  816. {
  817. return sqlsrv_fetch_object($cursor ? $cursor : $this->cursor, $class);
  818. }
  819. /**
  820. * Method to free up the memory used for the result set.
  821. *
  822. * @param mixed $cursor The optional result set cursor from which to fetch the row.
  823. *
  824. * @return void
  825. *
  826. * @since 1.0
  827. */
  828. protected function freeResult($cursor = null)
  829. {
  830. sqlsrv_free_stmt($cursor ? $cursor : $this->cursor);
  831. }
  832. /**
  833. * Method to check and see if a field exists in a table.
  834. *
  835. * @param string $table The table in which to verify the field.
  836. * @param string $field The field to verify.
  837. *
  838. * @return boolean True if the field exists in the table.
  839. *
  840. * @since 1.0
  841. */
  842. protected function checkFieldExists($table, $field)
  843. {
  844. $this->connect();
  845. $table = $this->replacePrefix((string) $table);
  846. $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS" . " WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" .
  847. " ORDER BY ORDINAL_POSITION";
  848. $this->setQuery($sql);
  849. if ($this->loadResult())
  850. {
  851. return true;
  852. }
  853. else
  854. {
  855. return false;
  856. }
  857. }
  858. /**
  859. * Method to wrap an SQL statement to provide a LIMIT and OFFSET behavior for scrolling through a result set.
  860. *
  861. * @param string $sql The SQL statement to process.
  862. * @param integer $limit The maximum affected rows to set.
  863. * @param integer $offset The affected row offset to set.
  864. *
  865. * @return string The processed SQL statement.
  866. *
  867. * @since 1.0
  868. */
  869. protected function limit($sql, $limit, $offset)
  870. {
  871. $orderBy = stristr($sql, 'ORDER BY');
  872. if (is_null($orderBy) || empty($orderBy))
  873. {
  874. $orderBy = 'ORDER BY (select 0)';
  875. }
  876. $sql = str_ireplace($orderBy, '', $sql);
  877. $rowNumberText = ',ROW_NUMBER() OVER (' . $orderBy . ') AS RowNumber FROM ';
  878. $sql = preg_replace('/\\s+FROM/', '\\1 ' . $rowNumberText . ' ', $sql, 1);
  879. $sql = 'SELECT TOP ' . $this->limit . ' * FROM (' . $sql . ') _myResults WHERE RowNumber > ' . $this->offset;
  880. return $sql;
  881. }
  882. /**
  883. * Renames a table in the database.
  884. *
  885. * @param string $oldTable The name of the table to be renamed
  886. * @param string $newTable The new name for the table.
  887. * @param string $backup Table prefix
  888. * @param string $prefix For the table - used to rename constraints in non-mysql databases
  889. *
  890. * @return SqlsrvDriver Returns this object to support chaining.
  891. *
  892. * @since 1.0
  893. * @throws \RuntimeException
  894. */
  895. public function renameTable($oldTable, $newTable, $backup = null, $prefix = null)
  896. {
  897. $constraints = array();
  898. if (!is_null($prefix) && !is_null($backup))
  899. {
  900. $constraints = $this->getTableConstraints($oldTable);
  901. }
  902. if (!empty($constraints))
  903. {
  904. $this->renameConstraints($constraints, $prefix, $backup);
  905. }
  906. $this->setQuery("sp_rename '" . $oldTable . "', '" . $newTable . "'");
  907. return $this->execute();
  908. }
  909. /**
  910. * Locks a table in the database.
  911. *
  912. * @param string $tableName The name of the table to lock.
  913. *
  914. * @return SqlsrvDriver Returns this object to support chaining.
  915. *
  916. * @since 1.0
  917. * @throws \RuntimeException
  918. */
  919. public function lockTable($tableName)
  920. {
  921. return $this;
  922. }
  923. /**
  924. * Unlocks tables in the database.
  925. *
  926. * @return SqlsrvDriver Returns this object to support chaining.
  927. *
  928. * @since 1.0
  929. * @throws \RuntimeException
  930. */
  931. public function unlockTables()
  932. {
  933. return $this;
  934. }
  935. }