MDB2
[ class tree: MDB2 ] [ index: MDB2 ] [ all elements ]

Source for file mssql.php

Documentation is available at mssql.php

  1. <?php
  2. // vim: set et ts=4 sw=4 fdm=marker:
  3. // +----------------------------------------------------------------------+
  4. // | PHP versions 4 and 5                                                 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
  7. // | Stig. S. Bakken, Lukas Smith, Frank M. Kromann                       |
  8. // | All rights reserved.                                                 |
  9. // +----------------------------------------------------------------------+
  10. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
  11. // | API as well as database abstraction for PHP applications.            |
  12. // | This LICENSE is in the BSD license style.                            |
  13. // |                                                                      |
  14. // | Redistribution and use in source and binary forms, with or without   |
  15. // | modification, are permitted provided that the following conditions   |
  16. // | are met:                                                             |
  17. // |                                                                      |
  18. // | Redistributions of source code must retain the above copyright       |
  19. // | notice, this list of conditions and the following disclaimer.        |
  20. // |                                                                      |
  21. // | Redistributions in binary form must reproduce the above copyright    |
  22. // | notice, this list of conditions and the following disclaimer in the  |
  23. // | documentation and/or other materials provided with the distribution. |
  24. // |                                                                      |
  25. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
  26. // | Lukas Smith nor the names of his contributors may be used to endorse |
  27. // | or promote products derived from this software without specific prior|
  28. // | written permission.                                                  |
  29. // |                                                                      |
  30. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
  31. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
  32. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
  33. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
  34. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
  35. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  36. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  37. // |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
  38. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
  39. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  40. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
  41. // | POSSIBILITY OF SUCH DAMAGE.                                          |
  42. // +----------------------------------------------------------------------+
  43. // | Author: Frank M. Kromann <frank@kromann.info>                        |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id: mssql.php 327310 2012-08-27 15:16:18Z danielc $
  47. //
  48. // {{{ Class MDB2_Driver_mssql
  49. /**
  50.  * MDB2 MSSQL Server driver
  51.  *
  52.  * @package MDB2
  53.  * @category Database
  54.  * @author  Frank M. Kromann <frank@kromann.info>
  55.  */
  56. class MDB2_Driver_mssql extends MDB2_Driver_Common
  57. {
  58.     // {{{ properties
  59.  
  60.     var $string_quoting = array('start' => "'"'end' => "'"'escape' => "'"'escape_pattern' => false);
  61.  
  62.     var $identifier_quoting = array('start' => '[''end' => ']''escape' => ']');
  63.  
  64.     // }}}
  65.     // {{{ constructor
  66.  
  67.     /**
  68.      * Constructor
  69.      */
  70.     function __construct()
  71.     {
  72.         parent::__construct();
  73.  
  74.         $this->phptype 'mssql';
  75.         $this->dbsyntax 'mssql';
  76.  
  77.         $this->supported['sequences''emulated';
  78.         $this->supported['indexes'= true;
  79.         $this->supported['affected_rows'= true;
  80.         $this->supported['transactions'= true;
  81.         $this->supported['savepoints'= false;
  82.         $this->supported['summary_functions'= true;
  83.         $this->supported['order_by_text'= true;
  84.         $this->supported['current_id''emulated';
  85.         $this->supported['limit_queries''emulated';
  86.         $this->supported['LOBs'= true;
  87.         $this->supported['replace''emulated';
  88.         $this->supported['sub_selects'= true;
  89.         $this->supported['triggers'= true;
  90.         $this->supported['auto_increment'= true;
  91.         $this->supported['primary_key'= true;
  92.         $this->supported['result_introspection'= true;
  93.         $this->supported['prepared_statements''emulated';
  94.         $this->supported['pattern_escaping'= true;
  95.         $this->supported['new_link'= true;
  96.  
  97.         $this->options['DBA_username'= false;
  98.         $this->options['DBA_password'= false;
  99.         $this->options['database_device'= false;
  100.         $this->options['database_size'= false;
  101.         $this->options['max_identifiers_length'= 128; // MS Access: 64
  102.     }
  103.  
  104.     // }}}
  105.     // {{{ errorInfo()
  106.  
  107.     /**
  108.      * This method is used to collect information about an error
  109.      *
  110.      * @param integer $error 
  111.      * @return array 
  112.      * @access public
  113.      */
  114.     function errorInfo($error = null$connection = null)
  115.     {
  116.         if (null === $connection{
  117.             $connection $this->connection;
  118.         }
  119.  
  120.         $native_code = null;
  121.         if ($connection{
  122.             $result @mssql_query('select @@ERROR as ErrorCode'$connection);
  123.             if ($result{
  124.                 $native_code @mssql_result($result00);
  125.                 @mssql_free_result($result);
  126.             }
  127.         }
  128.         $native_msg @mssql_get_last_message();
  129.         if (null === $error{
  130.             static $ecode_map;
  131.             if (empty($ecode_map)) {
  132.                 $ecode_map = array(
  133.                     102   => MDB2_ERROR_SYNTAX,
  134.                     110   => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  135.                     155   => MDB2_ERROR_NOSUCHFIELD,
  136.                     156   => MDB2_ERROR_SYNTAX,
  137.                     170   => MDB2_ERROR_SYNTAX,
  138.                     207   => MDB2_ERROR_NOSUCHFIELD,
  139.                     208   => MDB2_ERROR_NOSUCHTABLE,
  140.                     245   => MDB2_ERROR_INVALID_NUMBER,
  141.                     319   => MDB2_ERROR_SYNTAX,
  142.                     321   => MDB2_ERROR_NOSUCHFIELD,
  143.                     325   => MDB2_ERROR_SYNTAX,
  144.                     336   => MDB2_ERROR_SYNTAX,
  145.                     515   => MDB2_ERROR_CONSTRAINT_NOT_NULL,
  146.                     547   => MDB2_ERROR_CONSTRAINT,
  147.                     911   => MDB2_ERROR_NOT_FOUND,
  148.                     1018  => MDB2_ERROR_SYNTAX,
  149.                     1035  => MDB2_ERROR_SYNTAX,
  150.                     1801  => MDB2_ERROR_ALREADY_EXISTS,
  151.                     1913  => MDB2_ERROR_ALREADY_EXISTS,
  152.                     2209  => MDB2_ERROR_SYNTAX,
  153.                     2223  => MDB2_ERROR_SYNTAX,
  154.                     2248  => MDB2_ERROR_SYNTAX,
  155.                     2256  => MDB2_ERROR_SYNTAX,
  156.                     2257  => MDB2_ERROR_SYNTAX,
  157.                     2627  => MDB2_ERROR_CONSTRAINT,
  158.                     2714  => MDB2_ERROR_ALREADY_EXISTS,
  159.                     3607  => MDB2_ERROR_DIVZERO,
  160.                     3701  => MDB2_ERROR_NOSUCHTABLE,
  161.                     7630  => MDB2_ERROR_SYNTAX,
  162.                     8134  => MDB2_ERROR_DIVZERO,
  163.                     9303  => MDB2_ERROR_SYNTAX,
  164.                     9317  => MDB2_ERROR_SYNTAX,
  165.                     9318  => MDB2_ERROR_SYNTAX,
  166.                     9331  => MDB2_ERROR_SYNTAX,
  167.                     9332  => MDB2_ERROR_SYNTAX,
  168.                     15253 => MDB2_ERROR_SYNTAX,
  169.                 );
  170.             }
  171.             if (isset($ecode_map[$native_code])) {
  172.                 if ($native_code == 3701
  173.                     && preg_match('/Cannot drop the index/i'$native_msg)
  174.                 {
  175.                    $error = MDB2_ERROR_NOT_FOUND;
  176.                 else {
  177.                     $error $ecode_map[$native_code];
  178.                 }
  179.             }
  180.         }
  181.         return array($error$native_code$native_msg);
  182.     }
  183.  
  184.     // }}}
  185.     // {{{ function escapePattern($text)
  186.  
  187.     /**
  188.      * Quotes pattern (% and _) characters in a string)
  189.      *
  190.      * @param   string  the input string to quote
  191.      *
  192.      * @return  string  quoted string
  193.      *
  194.      * @access  public
  195.      */
  196.     function escapePattern($text)
  197.     {
  198.         $text str_replace("[""[ [ ]"$text);
  199.         foreach ($this->wildcards as $wildcard{
  200.             $text str_replace($wildcard'[' $wildcard ']'$text);
  201.         }
  202.         return $text;
  203.     }
  204.  
  205.     // }}}
  206.     // {{{ escape()
  207.  
  208.     /**
  209.      * Quotes a string so it can be safely used in a query. It will quote
  210.      * the text so it can safely be used within a query.
  211.      *
  212.      * @param string $text             the input string to quote
  213.      * @param bool   $escape_wildcards flag
  214.      *
  215.      * @return string  quoted string
  216.      * @access public
  217.      */
  218.     function escape($text$escape_wildcards = false)
  219.     {
  220.         $text = parent::escape($text$escape_wildcards);
  221.         // http://pear.php.net/bugs/bug.php?id=16118
  222.         // http://support.microsoft.com/kb/164291
  223.         return preg_replace("/\\\\(\r\n|\r|\n)/"'\\\\$1'$text);
  224.     }
  225.  
  226.     // }}}
  227.     // {{{ beginTransaction()
  228.  
  229.     /**
  230.      * Start a transaction or set a savepoint.
  231.      *
  232.      * @param string $savepoint name of a savepoint to set
  233.      *
  234.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  235.      * @access public
  236.      */
  237.     function beginTransaction($savepoint = null)
  238.     {
  239.         $this->debug('Starting transaction/savepoint'__FUNCTION__array('is_manip' => true'savepoint' => $savepoint));
  240.         if (null !== $savepoint{
  241.             if (!$this->in_transaction{
  242.                 return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  243.                     'savepoint cannot be released when changes are auto committed'__FUNCTION__);
  244.             }
  245.             $query 'SAVE TRANSACTION '.$savepoint;
  246.             return $this->_doQuery($querytrue);
  247.         }
  248.         if ($this->in_transaction{
  249.             return MDB2_OK;  //nothing to do
  250.         }
  251.         if (!$this->destructor_registered && $this->opened_persistent{
  252.             $this->destructor_registered = true;
  253.             register_shutdown_function('MDB2_closeOpenTransactions');
  254.         }
  255.         $result =$this->_doQuery('BEGIN TRANSACTION'true);
  256.         if (MDB2::isError($result)) {
  257.             return $result;
  258.         }
  259.         $this->in_transaction = true;
  260.         return MDB2_OK;
  261.     }
  262.  
  263.     // }}}
  264.     // {{{ commit()
  265.  
  266.     /**
  267.      * Commit the database changes done during a transaction that is in
  268.      * progress or release a savepoint. This function may only be called when
  269.      * auto-committing is disabled, otherwise it will fail. Therefore, a new
  270.      * transaction is implicitly started after committing the pending changes.
  271.      *
  272.      * @param string $savepoint name of a savepoint to release
  273.      *
  274.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  275.      * @access  public
  276.      */
  277.     function commit($savepoint = null)
  278.     {
  279.         $this->debug('Committing transaction/savepoint'__FUNCTION__array('is_manip' => true'savepoint' => $savepoint));
  280.         if (!$this->in_transaction{
  281.             return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  282.                 'commit/release savepoint cannot be done changes are auto committed'__FUNCTION__);
  283.         }
  284.         if (null !== $savepoint{
  285.             return MDB2_OK;
  286.         }
  287.  
  288.         $result =$this->_doQuery('COMMIT TRANSACTION'true);
  289.         if (MDB2::isError($result)) {
  290.             return $result;
  291.         }
  292.         $this->in_transaction = false;
  293.         return MDB2_OK;
  294.     }
  295.  
  296.     // }}}
  297.     // {{{ rollback()
  298.  
  299.     /**
  300.      * Cancel any database changes done during a transaction or since a specific
  301.      * savepoint that is in progress. This function may only be called when
  302.      * auto-committing is disabled, otherwise it will fail. Therefore, a new
  303.      * transaction is implicitly started after canceling the pending changes.
  304.      *
  305.      * @param string $savepoint name of a savepoint to rollback to
  306.      *
  307.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  308.      * @access public
  309.      */
  310.     function rollback($savepoint = null)
  311.     {
  312.         $this->debug('Rolling back transaction/savepoint'__FUNCTION__array('is_manip' => true'savepoint' => $savepoint));
  313.         if (!$this->in_transaction{
  314.             return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  315.                 'rollback cannot be done changes are auto committed'__FUNCTION__);
  316.         }
  317.         if (null !== $savepoint{
  318.             $query 'ROLLBACK TRANSACTION '.$savepoint;
  319.             return $this->_doQuery($querytrue);
  320.         }
  321.  
  322.         $result =$this->_doQuery('ROLLBACK TRANSACTION'true);
  323.         if (MDB2::isError($result)) {
  324.             return $result;
  325.         }
  326.         $this->in_transaction = false;
  327.         return MDB2_OK;
  328.     }
  329.  
  330.     // }}}
  331.     // {{{ _doConnect()
  332.  
  333.     /**
  334.      * do the grunt work of the connect
  335.      *
  336.      * @param string  $username 
  337.      * @param string  $password 
  338.      * @param boolean $persistent 
  339.      *
  340.      * @return connection on success or MDB2 Error Object on failure
  341.      * @access protected
  342.      */
  343.     function _doConnect($username$password$persistent = false)
  344.     {
  345.         if (   !extension_loaded($this->phptype)
  346.             && !extension_loaded('sybase_ct')
  347.             && !extension_loaded('odbtp')
  348.             && !function_exists('mssql_connect')
  349.         {
  350.             return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  351.                 'extension '.$this->phptype.' is not compiled into PHP'__FUNCTION__);
  352.         }
  353.  
  354.         $params = array(
  355.             $this->dsn['hostspec'$this->dsn['hostspec''localhost',
  356.             $username $username : null,
  357.             $password $password : null,
  358.             );
  359.         if ($this->dsn['port']{
  360.             $params[0].= ((substr(PHP_OS03== 'WIN'',' ':').$this->dsn['port'];
  361.         }
  362.         if (!$persistent{
  363.             if ($this->_isNewLinkSet()) {
  364.                 $params[= true;
  365.             else {
  366.                 $params[= false;
  367.             }
  368.         }
  369.  
  370.         $connect_function $persistent 'mssql_pconnect' 'mssql_connect';
  371.  
  372.         $connection @call_user_func_array($connect_function$params);
  373.         if ($connection <= 0{
  374.             return $this->raiseError(MDB2_ERROR_CONNECT_FAILEDnullnull,
  375.                 'unable to establish a connection'__FUNCTION____FUNCTION__);
  376.         }
  377.  
  378.         @mssql_query('SET ANSI_NULL_DFLT_ON ON'$connection);
  379.  
  380.         /*
  381.         if (!empty($this->dsn['charset'])) {
  382.             $result = $this->setCharset($this->dsn['charset'], $connection);
  383.             if (MDB2::isError($result)) {
  384.                 return $result;
  385.             }
  386.         }
  387.         */
  388.  
  389.         if ((bool)ini_get('mssql.datetimeconvert')) {
  390.             // his isn't the most elegant way of doing it but it prevents from
  391.             // breaking anything thus preserves BC. Bug #11849
  392.             if (isset($this->options['datetimeconvert']&& (bool)$this->options['datetimeconvert'!== false{
  393.                 @ini_set('mssql.datetimeconvert''1');
  394.             else {
  395.                 @ini_set('mssql.datetimeconvert''0');
  396.             }
  397.         }
  398.  
  399.         if (empty($this->dsn['disable_iso_date'])) {
  400.             @mssql_query('SET DATEFORMAT ymd'$connection);
  401.         }
  402.  
  403.         return $connection;
  404.     }
  405.  
  406.     // }}}
  407.     // {{{ connect()
  408.  
  409.     /**
  410.      * Connect to the database
  411.      *
  412.      * @return true on success, MDB2 Error Object on failure
  413.      */
  414.     function connect()
  415.     {
  416.         if (is_resource($this->connection)) {
  417.             //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
  418.             if (MDB2::areEquals($this->connected_dsn$this->dsn)
  419.                 && $this->opened_persistent == $this->options['persistent']
  420.             {
  421.                 return MDB2_OK;
  422.             }
  423.             $this->disconnect(false);
  424.         }
  425.  
  426.         $connection $this->_doConnect(
  427.             $this->dsn['username'],
  428.             $this->dsn['password'],
  429.             $this->options['persistent']
  430.         );
  431.         if (MDB2::isError($connection)) {
  432.             return $connection;
  433.         }
  434.  
  435.         $this->connection $connection;
  436.         $this->connected_dsn $this->dsn;
  437.         $this->connected_database_name '';
  438.         $this->opened_persistent $this->options['persistent'];
  439.         $this->dbsyntax $this->dsn['dbsyntax'$this->dsn['dbsyntax'$this->phptype;
  440.  
  441.         if ($this->database_name{
  442.             if ($this->database_name != $this->connected_database_name{
  443.                 if (!@mssql_select_db($this->database_name$connection)) {
  444.                     $err $this->raiseError(nullnullnull,
  445.                         'Could not select the database: '.$this->database_name__FUNCTION__);
  446.                     return $err;
  447.                 }
  448.                 $this->connected_database_name $this->database_name;
  449.             }
  450.         }
  451.  
  452.         return MDB2_OK;
  453.     }
  454.  
  455.     // }}}
  456.     // {{{ databaseExists()
  457.  
  458.     /**
  459.      * check if given database name is exists?
  460.      *
  461.      * @param string $name    name of the database that should be checked
  462.      *
  463.      * @return mixed true/false on success, a MDB2 error on failure
  464.      * @access public
  465.      */
  466.     function databaseExists($name)
  467.     {
  468.         $connection $this->_doConnect($this->dsn['username'],
  469.                                         $this->dsn['password'],
  470.                                         $this->options['persistent']);
  471.         if (MDB2::isError($connection)) {
  472.             return $connection;
  473.         }
  474.  
  475.         $result @mssql_select_db($name$connection);
  476.         $errorInfo $this->errorInfo(null$connection);
  477.         @mssql_close($connection);
  478.         if (!$result{
  479.             if ($errorInfo[0!= MDB2_ERROR_NOT_FOUND{
  480.             exit;
  481.                 $result $this->raiseError($errorInfo[0]nullnull$errorInfo[2]__FUNCTION__);
  482.                 return $result;
  483.             }
  484.             $result = false;
  485.         }
  486.  
  487.         return $result;
  488.     }
  489.  
  490.     // }}}
  491.     // {{{ disconnect()
  492.  
  493.     /**
  494.      * Log out and disconnect from the database.
  495.      *
  496.      * @param  boolean $force if the disconnect should be forced even if the
  497.      *                         connection is opened persistently
  498.      * @return mixed true on success, false if not connected and error
  499.      *                 object on error
  500.      * @access public
  501.      */
  502.     function disconnect($force = true)
  503.     {
  504.         if (is_resource($this->connection)) {
  505.             if ($this->in_transaction{
  506.                 $dsn $this->dsn;
  507.                 $database_name $this->database_name;
  508.                 $persistent $this->options['persistent'];
  509.                 $this->dsn $this->connected_dsn;
  510.                 $this->database_name $this->connected_database_name;
  511.                 $this->options['persistent'$this->opened_persistent;
  512.                 $this->rollback();
  513.                 $this->dsn $dsn;
  514.                 $this->database_name $database_name;
  515.                 $this->options['persistent'$persistent;
  516.             }
  517.  
  518.             if (!$this->opened_persistent || $force{
  519.                 $ok @mssql_close($this->connection);
  520.                 if (!$ok{
  521.                     return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
  522.                            nullnullnull__FUNCTION__);
  523.                 }
  524.             }
  525.         else {
  526.             return false;
  527.         }
  528.         return parent::disconnect($force);
  529.     }
  530.  
  531.     // }}}
  532.     // {{{ standaloneQuery()
  533.  
  534.     /**
  535.      * execute a query as DBA
  536.      *
  537.      * @param string $query the SQL query
  538.      * @param mixed   $types  array that contains the types of the columns in
  539.      *                         the result set
  540.      * @param boolean $is_manip  if the query is a manipulation query
  541.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  542.      * @access public
  543.      */
  544.     function standaloneQuery($query$types = null$is_manip = false)
  545.     {
  546.         $user $this->options['DBA_username']$this->options['DBA_username'$this->dsn['username'];
  547.         $pass $this->options['DBA_password']$this->options['DBA_password'$this->dsn['password'];
  548.         $connection $this->_doConnect($user$pass$this->options['persistent']);
  549.         if (MDB2::isError($connection)) {
  550.             return $connection;
  551.         }
  552.  
  553.         $offset $this->offset;
  554.         $limit $this->limit;
  555.         $this->offset $this->limit = 0;
  556.         $query $this->_modifyQuery($query$is_manip$limit$offset);
  557.  
  558.         $result $this->_doQuery($query$is_manip$connection$this->database_name);
  559.         if (!MDB2::isError($result)) {
  560.             $result $this->_affectedRows($connection$result);
  561.         }
  562.  
  563.         @mssql_close($connection);
  564.         return $result;
  565.     }
  566.  
  567.     // }}}
  568.     // {{{ _doQuery()
  569.  
  570.     /**
  571.      * Execute a query
  572.      * @param string $query  query
  573.      * @param boolean $is_manip  if the query is a manipulation query
  574.      * @param resource $connection 
  575.      * @param string $database_name 
  576.      * @return result or error object
  577.      * @access protected
  578.      */
  579.     function _doQuery($query$is_manip = false$connection = null$database_name = null)
  580.     {
  581.         $this->last_query $query;
  582.         $result $this->debug($query'query'array('is_manip' => $is_manip'when' => 'pre'));
  583.         if ($result{
  584.             if (MDB2::isError($result)) {
  585.                 return $result;
  586.             }
  587.             $query $result;
  588.         }
  589.         if ($this->options['disable_query']{
  590.             $result $is_manip ? 0 : null;
  591.             return $result;
  592.         }
  593.  
  594.         if (null === $connection{
  595.             $connection $this->getConnection();
  596.             if (MDB2::isError($connection)) {
  597.                 return $connection;
  598.             }
  599.         }
  600.         if (null === $database_name{
  601.             $database_name $this->database_name;
  602.         }
  603.  
  604.         if ($database_name{
  605.             if ($database_name != $this->connected_database_name{
  606.                 if (!@mssql_select_db($database_name$connection)) {
  607.                     $err $this->raiseError(nullnullnull,
  608.                         'Could not select the database: '.$database_name__FUNCTION__);
  609.                     return $err;
  610.                 }
  611.                 $this->connected_database_name $database_name;
  612.             }
  613.         }
  614.  
  615.         $result @mssql_query($query$connection);
  616.         if (!$result{
  617.             $err $this->raiseError(nullnullnull,
  618.                 'Could not execute statement'__FUNCTION__);
  619.             return $err;
  620.         }
  621.  
  622.         $this->debug($query'query'array('is_manip' => $is_manip'when' => 'post''result' => $result));
  623.         return $result;
  624.     }
  625.  
  626.     // }}}
  627.     // {{{ _affectedRows()
  628.  
  629.     /**
  630.      * Returns the number of rows affected
  631.      *
  632.      * @param resource $result 
  633.      * @param resource $connection 
  634.      * @return mixed MDB2 Error Object or the number of rows affected
  635.      * @access private
  636.      */
  637.     function _affectedRows($connection$result = null)
  638.     {
  639.         if (null === $connection{
  640.             $connection $this->getConnection();
  641.             if (MDB2::isError($connection)) {
  642.                 return $connection;
  643.             }
  644.         }
  645.         return @mssql_rows_affected($connection);
  646.     }
  647.  
  648.     // }}}
  649.     // {{{ _modifyQuery()
  650.  
  651.     /**
  652.      * Changes a query string for various DBMS specific reasons
  653.      *
  654.      * @param string $query  query to modify
  655.      * @param boolean $is_manip  if it is a DML query
  656.      * @param integer $limit  limit the number of rows
  657.      * @param integer $offset  start reading from given offset
  658.      * @return string modified query
  659.      * @access protected
  660.      */
  661.     function _modifyQuery($query$is_manip$limit$offset)
  662.     {
  663.         if ($limit > 0{
  664.             $fetch $offset $limit;
  665.             if (!$is_manip{
  666.                 return preg_replace('/^([\s(])*SELECT( DISTINCT)?(?!\s*TOP\s*\()/i',
  667.                     "\\1SELECT\\2 TOP $fetch"$query);
  668.             }
  669.         }
  670.         return $query;
  671.     }
  672.  
  673.     // }}}
  674.     // {{{ getServerVersion()
  675.  
  676.     /**
  677.      * return version information about the server
  678.      *
  679.      * @param bool   $native  determines if the raw version string should be returned
  680.      * @return mixed array/string with version information or MDB2 error object
  681.      * @access public
  682.      */
  683.     function getServerVersion($native = false)
  684.     {
  685.         if ($this->connected_server_info{
  686.             $server_info $this->connected_server_info;
  687.         else {
  688.             $query 'SELECT @@VERSION';
  689.             $server_info $this->queryOne($query'text');
  690.             if (MDB2::isError($server_info)) {
  691.                 return $server_info;
  692.             }
  693.         }
  694.         // cache server_info
  695.         $this->connected_server_info $server_info;
  696.         if (!$native && !MDB2::isError($server_info)) {
  697.             if (preg_match('/(\d+)\.(\d+)\.(\d+)/'$server_info$tmp)) {
  698.                 $server_info = array(
  699.                     'major' => $tmp[1],
  700.                     'minor' => $tmp[2],
  701.                     'patch' => $tmp[3],
  702.                     'extra' => null,
  703.                     'native' => $server_info,
  704.                 );
  705.             else {
  706.                 $server_info = array(
  707.                     'major' => null,
  708.                     'minor' => null,
  709.                     'patch' => null,
  710.                     'extra' => null,
  711.                     'native' => $server_info,
  712.                 );
  713.             }
  714.         }
  715.         return $server_info;
  716.     }
  717.  
  718.     // }}}
  719.     // {{{ _checkSequence
  720.  
  721.     /**
  722.      * Checks if there's a sequence that exists.
  723.      *
  724.      * @param  string $seq_name    The sequence name to verify.
  725.      * @return bool   $tableExists The value if the table exists or not
  726.      * @access private
  727.      */
  728.     function _checkSequence($seq_name)
  729.     {
  730.         $query = "SELECT * FROM $seq_name";
  731.         $tableExists $this->_doQuery($querytrue);
  732.         if (MDB2::isError($tableExists)) {
  733.             if ($tableExists->getCode(== MDB2_ERROR_NOSUCHTABLE{
  734.                 return false;
  735.             }
  736.             //return $tableExists;
  737.             return false;
  738.         }
  739.         return mssql_result($tableExists00);
  740.     }
  741.  
  742.     // }}}
  743.     // {{{ nextID()
  744.  
  745.     /**
  746.      * Returns the next free id of a sequence
  747.      *
  748.      * @param string $seq_name name of the sequence
  749.      * @param boolean $ondemand when true the sequence is
  750.      *                           automatic created, if it
  751.      *                           not exists
  752.      *
  753.      * @return mixed MDB2 Error Object or id
  754.      * @access public
  755.      */
  756.     function nextID($seq_name$ondemand = true)
  757.     {
  758.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  759.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  760.         $this->pushErrorHandling(PEAR_ERROR_RETURN);
  761.         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  762.  
  763.         $seq_val $this->_checkSequence($sequence_name);
  764.  
  765.         if ($seq_val{
  766.             $query = "SET IDENTITY_INSERT $sequence_name OFF ".
  767.                      "INSERT INTO $sequence_name DEFAULT VALUES";
  768.         else {
  769.             $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (0)";
  770.         }
  771.         $result $this->_doQuery($querytrue);
  772.         $this->popExpect();
  773.         $this->popErrorHandling();
  774.         if (MDB2::isError($result)) {
  775.             if ($ondemand && !$this->_checkSequence($sequence_name)) {
  776.                 $this->loadModule('Manager'nulltrue);
  777.                 $result $this->manager->createSequence($seq_name);
  778.                 if (MDB2::isError($result)) {
  779.                     return $this->raiseError($resultnullnull,
  780.                         'on demand sequence '.$seq_name.' could not be created'__FUNCTION__);
  781.                 else {
  782.                     /**
  783.                      * Little off-by-one problem with the sequence emulation
  784.                      * here being fixed, that instead of re-calling nextID
  785.                      * and forcing an increment by one, we simply check if it
  786.                      * exists, then we get the last inserted id if it does.
  787.                      *
  788.                      * In theory, $seq_name should be created otherwise there would
  789.                      * have been an error thrown somewhere up there..
  790.                      *
  791.                      * @todo confirm
  792.                      */
  793.                     if ($this->_checkSequence($seq_name)) {
  794.                         return $this->lastInsertID($seq_name);
  795.                     }
  796.  
  797.                     return $this->nextID($seq_namefalse);
  798.                 }
  799.             }
  800.             return $result;
  801.         }
  802.         $value $this->lastInsertID($sequence_name);
  803.         if (is_numeric($value)) {
  804.             $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  805.             $result $this->_doQuery($querytrue);
  806.             if (MDB2::isError($result)) {
  807.                 $this->warnings['nextID: could not delete previous sequence table values from '.$seq_name;
  808.             }
  809.         }
  810.         return $value;
  811.     }
  812.  
  813.     // }}}
  814.     // {{{ lastInsertID()
  815.  
  816.     /**
  817.      * Returns the autoincrement ID if supported or $id or fetches the current
  818.      * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  819.      *
  820.      * @param string $table name of the table into which a new row was inserted
  821.      * @param string $field name of the field into which a new row was inserted
  822.      *
  823.      * @return mixed MDB2 Error Object or id
  824.      * @access public
  825.      */
  826.     function lastInsertID($table = null$field = null)
  827.     {
  828.         $server_info $this->getServerVersion();
  829.         if (is_array($server_info&& (null !== $server_info['major'])
  830.            && $server_info['major'>= 8
  831.         {
  832.             $query = "SELECT IDENT_CURRENT('$table')";
  833.         else {
  834.             $query "SELECT @@IDENTITY";
  835.             if (null !== $table{
  836.                 $query .= ' FROM '.$this->quoteIdentifier($tabletrue);
  837.             }
  838.         }
  839.  
  840.         return $this->queryOne($query'integer');
  841.     }
  842.  
  843.     // }}}
  844. }
  845.  
  846. // }}}
  847. // {{{ Class MDB2_Result_mssql
  848.  
  849. /**
  850.  * MDB2 MSSQL Server result driver
  851.  *
  852.  * @package MDB2
  853.  * @category Database
  854.  * @author  Frank M. Kromann <frank@kromann.info>
  855.  */
  856. class MDB2_Result_mssql extends MDB2_Result_Common
  857. {
  858.     // {{{ _skipLimitOffset()
  859.  
  860.     /**
  861.      * Skip the first row of a result set.
  862.      *
  863.      * @param resource $result 
  864.      * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  865.      * @access protected
  866.      */
  867.     function _skipLimitOffset()
  868.     {
  869.         if ($this->limit{
  870.             if ($this->rownum >= $this->limit{
  871.                 return false;
  872.             }
  873.         }
  874.         if ($this->offset{
  875.             while ($this->offset_count $this->offset{
  876.                 ++$this->offset_count;
  877.                 if (!is_array(@mssql_fetch_row($this->result))) {
  878.                     $this->offset_count $this->limit;
  879.                     return false;
  880.                 }
  881.             }
  882.         }
  883.         return MDB2_OK;
  884.     }
  885.  
  886.     // }}}
  887.     // {{{ fetchRow()
  888.  
  889.     /**
  890.      * Fetch a row and insert the data into an existing array.
  891.      *
  892.      * @param int $fetchmode  how the array data should be indexed
  893.      * @param int $rownum     number of the row where the data can be found
  894.      *
  895.      * @return int data array on success, a MDB2 error on failure
  896.      * @access public
  897.      */
  898.     function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  899.     {
  900.         if (!$this->_skipLimitOffset()) {
  901.             return null;
  902.         }
  903.         if (null !== $rownum{
  904.             $seek $this->seek($rownum);
  905.             if (MDB2::isError($seek)) {
  906.                 return $seek;
  907.             }
  908.         }
  909.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  910.             $fetchmode $this->db->fetchmode;
  911.         }
  912.         if (   $fetchmode == MDB2_FETCHMODE_ASSOC
  913.             || $fetchmode == MDB2_FETCHMODE_OBJECT
  914.         {
  915.             $row @mssql_fetch_assoc($this->result);
  916.             if (is_array($row)
  917.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  918.             {
  919.                 $row array_change_key_case($row$this->db->options['field_case']);
  920.             }
  921.         else {
  922.             $row @mssql_fetch_row($this->result);
  923.         }
  924.         if (!$row{
  925.             if (false === $this->result{
  926.                 $err $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  927.                     'resultset has already been freed'__FUNCTION__);
  928.                 return $err;
  929.             }
  930.             return null;
  931.         }
  932.         $mode $this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL;
  933.         $rtrim = false;
  934.         if ($this->db->options['portability'MDB2_PORTABILITY_RTRIM{
  935.             if (empty($this->types)) {
  936.                 $mode += MDB2_PORTABILITY_RTRIM;
  937.             else {
  938.                 $rtrim = true;
  939.             }
  940.         }
  941.         if ($mode{
  942.             $this->db->_fixResultArrayValues($row$mode);
  943.         }
  944.         if (   (   $fetchmode != MDB2_FETCHMODE_ASSOC
  945.                 && $fetchmode != MDB2_FETCHMODE_OBJECT)
  946.             && !empty($this->types)
  947.         {
  948.             $row $this->db->datatype->convertResultRow($this->types$row$rtrim);
  949.         elseif (($fetchmode == MDB2_FETCHMODE_ASSOC
  950.                 || $fetchmode == MDB2_FETCHMODE_OBJECT)
  951.             && !empty($this->types_assoc)
  952.         {
  953.             $row $this->db->datatype->convertResultRow($this->types_assoc$row$rtrim);
  954.         }
  955.         if (!empty($this->values)) {
  956.             $this->_assignBindColumns($row);
  957.         }
  958.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  959.             $object_class $this->db->options['fetch_class'];
  960.             if ($object_class == 'stdClass'{
  961.                 $row = (object) $row;
  962.             else {
  963.                 $rowObj = new $object_class($row);
  964.                 $row $rowObj;
  965.             }
  966.         }
  967.         ++$this->rownum;
  968.         return $row;
  969.     }
  970.  
  971.     // }}}
  972.     // {{{ _getColumnNames()
  973.  
  974.     /**
  975.      * Retrieve the names of columns returned by the DBMS in a query result.
  976.      *
  977.      * @return  mixed   Array variable that holds the names of columns as keys
  978.      *                   or an MDB2 error on failure.
  979.      *                   Some DBMS may not return any columns when the result set
  980.      *                   does not contain any rows.
  981.      * @access private
  982.      */
  983.     function _getColumnNames()
  984.     {
  985.         $columns = array();
  986.         $numcols $this->numCols();
  987.         if (MDB2::isError($numcols)) {
  988.             return $numcols;
  989.         }
  990.         for ($column = 0; $column $numcols$column++{
  991.             $column_name @mssql_field_name($this->result$column);
  992.             $columns[$column_name$column;
  993.         }
  994.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  995.             $columns array_change_key_case($columns$this->db->options['field_case']);
  996.         }
  997.         return $columns;
  998.     }
  999.  
  1000.     // }}}
  1001.     // {{{ numCols()
  1002.  
  1003.     /**
  1004.      * Count the number of columns returned by the DBMS in a query result.
  1005.      *
  1006.      * @return mixed integer value with the number of columns, a MDB2 error
  1007.      *       on failure
  1008.      * @access public
  1009.      */
  1010.     function numCols()
  1011.     {
  1012.         $cols @mssql_num_fields($this->result);
  1013.         if (null === $cols{
  1014.             if (false === $this->result{
  1015.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1016.                     'resultset has already been freed'__FUNCTION__);
  1017.             }
  1018.             if (null === $this->result{
  1019.                 return count($this->types);
  1020.             }
  1021.             return $this->db->raiseError(nullnullnull,
  1022.                 'Could not get column count'__FUNCTION__);
  1023.         }
  1024.         return $cols;
  1025.     }
  1026.  
  1027.     // }}}
  1028.     // {{{ nextResult()
  1029.  
  1030.     /**
  1031.      * Move the internal result pointer to the next available result
  1032.      *
  1033.      * @return true on success, false if there is no more result set or an error object on failure
  1034.      * @access public
  1035.      */
  1036.     function nextResult()
  1037.     {
  1038.         if (false === $this->result{
  1039.             return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1040.                 'resultset has already been freed'__FUNCTION__);
  1041.         }
  1042.         if (null === $this->result{
  1043.             return false;
  1044.         }
  1045.         return @mssql_next_result($this->result);
  1046.     }
  1047.  
  1048.     // }}}
  1049.     // {{{ free()
  1050.  
  1051.     /**
  1052.      * Free the internal resources associated with $result.
  1053.      *
  1054.      * @return boolean true on success, false if $result is invalid
  1055.      * @access public
  1056.      */
  1057.     function free()
  1058.     {
  1059.         if (is_resource($this->result&& $this->db->connection{
  1060.             $free @mssql_free_result($this->result);
  1061.             if (false === $free{
  1062.                 return $this->db->raiseError(nullnullnull,
  1063.                     'Could not free result'__FUNCTION__);
  1064.             }
  1065.         }
  1066.         $this->result = false;
  1067.         return MDB2_OK;
  1068.     }
  1069.  
  1070.     // }}}
  1071. }
  1072.  
  1073. // }}}
  1074. // {{{ class MDB2_BufferedResult_mssql
  1075.  
  1076. /**
  1077.  * MDB2 MSSQL Server buffered result driver
  1078.  *
  1079.  * @package MDB2
  1080.  * @category Database
  1081.  * @author  Frank M. Kromann <frank@kromann.info>
  1082.  */
  1083. {
  1084.     // {{{ seek()
  1085.  
  1086.     /**
  1087.      * Seek to a specific row in a result set
  1088.      *
  1089.      * @param int $rownum number of the row where the data can be found
  1090.      *
  1091.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1092.      * @access public
  1093.      */
  1094.     function seek($rownum = 0)
  1095.     {
  1096.         if ($this->rownum != ($rownum - 1&& !@mssql_data_seek($this->result$rownum)) {
  1097.             if (false === $this->result{
  1098.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1099.                     'resultset has already been freed'__FUNCTION__);
  1100.             }
  1101.             if (null === $this->result{
  1102.                 return MDB2_OK;
  1103.             }
  1104.             return $this->db->raiseError(MDB2_ERROR_INVALIDnullnull,
  1105.                 'tried to seek to an invalid row number ('.$rownum.')'__FUNCTION__);
  1106.         }
  1107.         $this->rownum $rownum - 1;
  1108.         return MDB2_OK;
  1109.     }
  1110.  
  1111.     // }}}
  1112.     // {{{ valid()
  1113.  
  1114.     /**
  1115.      * Check if the end of the result set has been reached
  1116.      *
  1117.      * @return mixed true or false on sucess, a MDB2 error on failure
  1118.      * @access public
  1119.      */
  1120.     function valid()
  1121.     {
  1122.         $numrows $this->numRows();
  1123.         if (MDB2::isError($numrows)) {
  1124.             return $numrows;
  1125.         }
  1126.         return $this->rownum ($numrows - 1);
  1127.     }
  1128.  
  1129.     // }}}
  1130.     // {{{ numRows()
  1131.  
  1132.     /**
  1133.      * Returns the number of rows in a result object
  1134.      *
  1135.      * @return mixed MDB2 Error Object or the number of rows
  1136.      * @access public
  1137.      */
  1138.     function numRows()
  1139.     {
  1140.         $rows @mssql_num_rows($this->result);
  1141.         if (null === $rows{
  1142.             if (false === $this->result{
  1143.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1144.                     'resultset has already been freed'__FUNCTION__);
  1145.             }
  1146.             if (null === $this->result{
  1147.                 return 0;
  1148.             }
  1149.             return $this->db->raiseError(nullnullnull,
  1150.                 'Could not get row count'__FUNCTION__);
  1151.         }
  1152.         if ($this->limit{
  1153.             $rows -= $this->offset;
  1154.             if ($rows $this->limit + 1{
  1155.                 $rows $this->limit + 1;
  1156.             }
  1157.             if ($rows < 0{
  1158.                 $rows = 0;
  1159.             }
  1160.         }
  1161.         return $rows;
  1162.     }
  1163. }
  1164.  
  1165. // }}}
  1166. // {{{ MDB2_Statement_mssql
  1167.  
  1168. /**
  1169.  * MDB2 MSSQL Server statement driver
  1170.  *
  1171.  * @package MDB2
  1172.  * @category Database
  1173.  * @author  Frank M. Kromann <frank@kromann.info>
  1174.  */
  1175. class MDB2_Statement_mssql extends MDB2_Statement_Common
  1176. {
  1177.  
  1178. }
  1179.  
  1180. // }}}
  1181. ?>

Documentation generated on Mon, 11 Mar 2019 15:51:11 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.