dbo_sybase.php

Go to the documentation of this file.
00001 <?php
00002 /* SVN FILE: $Id: dbo__sybase_8php-source.html 580 2008-07-01 14:45:49Z gwoo $ */
00003 /**
00004  * Sybase layer for DBO
00005  *
00006  * Long description for file
00007  *
00008  * PHP versions 4 and 5
00009  *
00010  * CakePHP(tm) :  Rapid Development Framework <http://www.cakephp.org/>
00011  * Copyright 2005-2008, Cake Software Foundation, Inc.
00012  *                              1785 E. Sahara Avenue, Suite 490-204
00013  *                              Las Vegas, Nevada 89104
00014  *
00015  * Licensed under The MIT License
00016  * Redistributions of files must retain the above copyright notice.
00017  *
00018  * @filesource
00019  * @copyright       Copyright 2005-2008, Cake Software Foundation, Inc.
00020  * @link                http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
00021  * @package         cake
00022  * @subpackage      cake.cake.libs.model.datasources.dbo
00023  * @since           CakePHP(tm) v 1.2.0.3097
00024  * @version         $Revision: 580 $
00025  * @modifiedby      $LastChangedBy: gwoo $
00026  * @lastmodified    $Date: 2008-07-01 09:45:49 -0500 (Tue, 01 Jul 2008) $
00027  * @license         http://www.opensource.org/licenses/mit-license.php The MIT License
00028  */
00029 /**
00030  * Short description for class.
00031  *
00032  * Long description for class
00033  *
00034  * @package     cake
00035  * @subpackage  cake.cake.libs.model.datasources.dbo
00036  */
00037 class DboSybase extends DboSource {
00038 /**
00039  * Driver description
00040  *
00041  * @var string
00042  */
00043     var $description = "Sybase DBO Driver";
00044 /**
00045  * Start quote for quoted identifiers
00046  *
00047  * @var string
00048  */
00049     var $startQuote = "";
00050 /**
00051  * End quote for quoted identifiers
00052  *
00053  * @var string
00054  */
00055     var $endQuote = "";
00056 /**
00057  * Base configuration settings for Sybase driver
00058  *
00059  * @var array
00060  */
00061     var $_baseConfig = array(
00062         'persistent' => true,
00063         'host' => 'localhost',
00064         'login' => 'sa',
00065         'password' => '',
00066         'database' => 'cake',
00067         'port' => '4100'
00068     );
00069 /**
00070  * Sybase column definition
00071  *
00072  * @var array
00073  */
00074     var $columns = array(
00075         'primary_key' => array('name' => 'numeric(9,0) IDENTITY PRIMARY KEY'),
00076         'string' => array('name' => 'varchar', 'limit' => '255'),
00077         'text' => array('name' => 'text'),
00078         'integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'),
00079         'float' => array('name' => 'float', 'formatter' => 'floatval'),
00080         'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
00081         'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
00082         'time' => array('name' => 'datetime', 'format' => 'H:i:s', 'formatter' => 'date'),
00083         'date' => array('name' => 'datetime', 'format' => 'Y-m-d', 'formatter' => 'date'),
00084         'binary' => array('name' => 'image'),
00085         'boolean' => array('name' => 'bit')
00086     );
00087 /**
00088  * Connects to the database using options in the given configuration array.
00089  *
00090  * @return boolean True if the database could be connected, else false
00091  */
00092     function connect() {
00093         $config = $this->config;
00094         $this->connected = false;
00095 
00096         if (!$config['persistent']) {
00097             $this->connection = sybase_connect($config['host'], $config['login'], $config['password'], true);
00098         } else {
00099             $this->connection = sybase_pconnect($config['host'], $config['login'], $config['password']);
00100         }
00101 
00102         if (sybase_select_db($config['database'], $this->connection)) {
00103             $this->connected = true;
00104         }
00105         return $this->connected;
00106     }
00107 /**
00108  * Disconnects from database.
00109  *
00110  * @return boolean True if the database could be disconnected, else false
00111  */
00112     function disconnect() {
00113         $this->connected = !@sybase_close($this->connection);
00114         return !$this->connected;
00115     }
00116 /**
00117  * Executes given SQL statement.
00118  *
00119  * @param string $sql SQL statement
00120  * @return resource Result resource identifier
00121  * @access protected
00122  */
00123     function _execute($sql) {
00124         return sybase_query($sql, $this->connection);
00125     }
00126 /**
00127  * Returns an array of sources (tables) in the database.
00128  *
00129  * @return array Array of tablenames in the database
00130  */
00131     function listSources() {
00132         $cache = parent::listSources();
00133         if ($cache != null) {
00134             return $cache;
00135         }
00136 
00137         $result = $this->_execute("select name from sysobjects where type='U'");
00138         if (!$result) {
00139             return array();
00140         } else {
00141 
00142             $tables = array();
00143             while ($line = sybase_fetch_array($result)) {
00144                 $tables[] = $line[0];
00145             }
00146 
00147             parent::listSources($tables);
00148             return $tables;
00149         }
00150     }
00151 /**
00152  * Returns an array of the fields in given table name.
00153  *
00154  * @param string $tableName Name of database table to inspect
00155  * @return array Fields in table. Keys are name and type
00156  */
00157     function describe(&$model) {
00158 
00159         $cache = parent::describe($model);
00160         if ($cache != null) {
00161             return $cache;
00162         }
00163 
00164         $fields = false;
00165         $cols = $this->query('DESC ' . $this->fullTableName($model));
00166 
00167         foreach ($cols as $column) {
00168             $colKey = array_keys($column);
00169             if (isset($column[$colKey[0]]) && !isset($column[0])) {
00170                 $column[0] = $column[$colKey[0]];
00171             }
00172             if (isset($column[0])) {
00173                 $fields[$column[0]['Field']] = array('type' => $this->column($column[0]['Type']),
00174                                                     'null' => $column[0]['Null'],
00175                                                     'length' => $this->length($column[0]['Type']),
00176                                                     );
00177             }
00178         }
00179 
00180         $this->__cacheDescription($model->tablePrefix.$model->table, $fields);
00181         return $fields;
00182     }
00183 /**
00184  * Returns a quoted and escaped string of $data for use in an SQL statement.
00185  *
00186  * @param string $data String to be prepared for use in an SQL statement
00187  * @param string $column The column into which this data will be inserted
00188  * @param boolean $safe Whether or not numeric data should be handled automagically if no column data is provided
00189  * @return string Quoted and escaped data
00190  */
00191     function value($data, $column = null, $safe = false) {
00192         $parent = parent::value($data, $column, $safe);
00193 
00194         if ($parent != null) {
00195             return $parent;
00196         }
00197 
00198         if ($data === null) {
00199             return 'NULL';
00200         }
00201 
00202         if ($data === '') {
00203             return  "''";
00204         }
00205 
00206         switch ($column) {
00207             case 'boolean':
00208                 $data = $this->boolean((bool)$data);
00209             break;
00210             default:
00211                 $data = str_replace("'", "''", $data);
00212             break;
00213         }
00214 
00215         return "'" . $data . "'";
00216     }
00217 /**
00218  * Begin a transaction
00219  *
00220  * @param unknown_type $model
00221  * @return boolean True on success, false on fail
00222  * (i.e. if the database/model does not support transactions).
00223  */
00224     function begin(&$model) {
00225         if (parent::begin($model)) {
00226             if ($this->execute('BEGIN TRAN')) {
00227                 $this->_transactionStarted = true;
00228                 return true;
00229             }
00230         }
00231         return false;
00232     }
00233 /**
00234  * Commit a transaction
00235  *
00236  * @param unknown_type $model
00237  * @return boolean True on success, false on fail
00238  * (i.e. if the database/model does not support transactions,
00239  * or a transaction has not started).
00240  */
00241     function commit(&$model) {
00242         if (parent::commit($model)) {
00243             $this->_transactionStarted = false;
00244             return $this->execute('COMMIT TRAN');
00245         }
00246         return false;
00247     }
00248 /**
00249  * Rollback a transaction
00250  *
00251  * @param unknown_type $model
00252  * @return boolean True on success, false on fail
00253  * (i.e. if the database/model does not support transactions,
00254  * or a transaction has not started).
00255  */
00256     function rollback(&$model) {
00257         if (parent::rollback($model)) {
00258             return $this->execute('ROLLBACK TRAN');
00259         }
00260         return false;
00261     }
00262 /**
00263  * Returns a formatted error message from previous database operation.
00264  *
00265  * @todo not implemented
00266  * @return string Error message with error number
00267  */
00268     function lastError() {
00269         return null;
00270     }
00271 /**
00272  * Returns number of affected rows in previous database operation. If no previous operation exists,
00273  * this returns false.
00274  *
00275  * @return integer Number of affected rows
00276  */
00277     function lastAffected() {
00278         if ($this->_result) {
00279             return sybase_affected_rows($this->connection);
00280         }
00281         return null;
00282     }
00283 /**
00284  * Returns number of rows in previous resultset. If no previous resultset exists,
00285  * this returns false.
00286  *
00287  * @return integer Number of rows in resultset
00288  */
00289     function lastNumRows() {
00290         if ($this->hasResult()) {
00291             return @sybase_num_rows($this->_result);
00292         }
00293         return null;
00294     }
00295 /**
00296  * Returns the ID generated from the previous INSERT operation.
00297  *
00298  * @param unknown_type $source
00299  * @return in
00300  */
00301     function lastInsertId($source = null) {
00302         $result=$this->fetchRow('SELECT @@IDENTITY');
00303         return $result[0];
00304     }
00305 /**
00306  * Converts database-layer column types to basic types
00307  *
00308  * @param string $real Real database-layer column type (i.e. "varchar(255)")
00309  * @return string Abstract column type (i.e. "string")
00310  */
00311     function column($real) {
00312         if (is_array($real)) {
00313             $col = $real['name'];
00314             if (isset($real['limit']))
00315             {
00316                 $col .= '('.$real['limit'].')';
00317             }
00318             return $col;
00319         }
00320 
00321         $col = str_replace(')', '', $real);
00322         $limit = null;
00323         if (strpos($col, '(') !== false) {
00324             list($col, $limit) = explode('(', $col);
00325         }
00326 
00327         if (in_array($col, array('datetime', 'smalldatetime'))) {
00328             return 'datetime';
00329         } elseif (in_array($col, array('int', 'bigint', 'smallint', 'tinyint'))) {
00330             return 'integer';
00331         } elseif (in_array($col, array('float', 'double', 'real', 'decimal', 'money', 'numeric', 'smallmoney'))) {
00332             return 'float';
00333         } elseif (strpos($col, 'text') !== false) {
00334             return 'text';
00335         } elseif (in_array($col, array('char', 'nchar', 'nvarchar', 'string', 'varchar'))) {
00336             return 'binary';
00337         } elseif (in_array($col, array('binary', 'image', 'varbinary'))) {
00338             return 'binary';
00339         }
00340 
00341         return 'text';
00342     }
00343 /**
00344  * Enter description here...
00345  *
00346  * @param unknown_type $results
00347  */
00348     function resultSet(&$results) {
00349         $this->results =& $results;
00350         $this->map = array();
00351         $num_fields = sybase_num_fields($results);
00352         $index = 0;
00353         $j = 0;
00354 
00355         while ($j < $num_fields) {
00356 
00357             $column = sybase_fetch_field($results,$j);
00358             if (!empty($column->table)) {
00359                 $this->map[$index++] = array($column->table, $column->name);
00360             } else {
00361                 $this->map[$index++] = array(0, $column->name);
00362             }
00363             $j++;
00364         }
00365     }
00366 /**
00367  * Fetches the next row from the current result set
00368  *
00369  * @return unknown
00370  */
00371     function fetchResult() {
00372         if ($row = sybase_fetch_row($this->results)) {
00373             $resultRow = array();
00374             $i = 0;
00375             foreach ($row as $index => $field) {
00376                 list($table, $column) = $this->map[$index];
00377                 $resultRow[$table][$column] = $row[$index];
00378                 $i++;
00379             }
00380             return $resultRow;
00381         } else {
00382             return false;
00383         }
00384     }
00385 }
00386 
00387 ?>