PageRenderTime 55ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/libraries/joomla/database/driver/sqlsrv.php

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