PageRenderTime 74ms CodeModel.GetById 43ms RepoModel.GetById 1ms app.codeStats 0ms

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

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